package com.ziyun.erp.modules.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.cloud.bus.core.EventBusPusher;
import com.cloud.bus.event.goods.BatchUpdateGoodsEvent;
import com.cloud.bus.event.goods.RefreshGoodsCacheEvent;
import com.cloud.bus.event.goods.UpdateGoodsCacheEvent;
import com.utility.New;
import com.ziyun.erp.common.utils.GoodsMonitorUtils;
import com.ziyun.erp.common.utils.JsonUtils;
import com.ziyun.erp.common.utils.UserUtils;
import com.ziyun.erp.modules.frozenGoods.entity.FrozenGoodsEntity;
import com.ziyun.erp.modules.frozenGoods.service.FrozenGoodsService;
import com.ziyun.erp.modules.goods.TwbVo.*;
import com.ziyun.erp.modules.goods.VO.AttributeVo;
import com.ziyun.erp.modules.goods.VO.FastPriceVo;
import com.ziyun.erp.modules.goods.VO.PrintPriceVo;
import com.ziyun.erp.modules.goods.VO.VerifyPriceVo;
import com.ziyun.erp.modules.goods.dao.GoodsDao;
import com.ziyun.erp.modules.goods.dao.GoodsOptionDao;
import com.ziyun.erp.modules.goods.dto.VerifyFastPriceDto;
import com.ziyun.erp.modules.goods.dto.VerifyPrintPriceDto;
import com.ziyun.erp.modules.goods.entity.*;
import com.ziyun.erp.modules.goods.service.GoodsAttributeService;
import com.ziyun.erp.modules.goods.service.GoodsProductService;
import com.ziyun.erp.modules.goods.service.GoodsService;
import com.ziyun.erp.modules.goods.service.GoodsTemplateService;
import com.ziyun.erp.modules.goodsCategory.entity.GoodsCategoryEntity;
import com.ziyun.erp.modules.goodsCategory.service.GoodsCategoryService;
import com.ziyun.erp.modules.goodsCraftPrice.entity.GoodsCraftPriceEntity;
import com.ziyun.erp.modules.goodsCraftPrice.service.GoodsCraftPriceService;
import com.ziyun.erp.modules.goodsImage.dao.GoodsImageDao;
import com.ziyun.erp.modules.goodsImage.entity.GoodsImageEntity;
import com.ziyun.erp.modules.goodsImage.service.GoodsImageService;
import com.ziyun.erp.modules.goodsMonitor.entity.GoodsMonitorEntity;
import com.ziyun.erp.modules.goodsMonitor.service.GoodsMonitorService;
import com.ziyun.erp.modules.productBaseInfo.entity.ProductBaseInfoEntity;
import com.ziyun.erp.modules.productBaseInfo.service.ProductBaseInfoService;
import com.ziyun.erp.modules.quoteAttribute.entity.QuoteAttributeOptionEntity;
import com.ziyun.erp.modules.quoteAttribute.service.QuoteAttributeOptionService;
import com.ziyun.erp.modules.quoteFactoryMaterial.entity.QuoteFactoryMaterialEntity;
import com.ziyun.erp.modules.quoteFactoryMaterial.service.QuoteFactoryMaterialService;
import com.ziyun.erp.modules.quoteProduct.entity.QuoteProductBaseInfoEntity;
import com.ziyun.erp.modules.quoteProduct.service.QuoteProductBaseInfoService;
import com.ziyun.erp.modules.quoteProduct.vo.QuoteProductBaseInfoVO;
import com.ziyun.erp.modules.store.storeGoodsCategory.entity.StoreGoodsCategoryTwdEntity;
import com.ziyun.erp.modules.store.storeGoodsCategory.service.StoreGoodsCategoryTwdService;
import com.ziyun.erp.modules.supp.entity.SellerInfoEntity;
import com.ziyun.erp.modules.unitLibrary.entity.UnitLibraryEntity;
import com.ziyun.erp.modules.unitLibrary.service.UnitLibraryService;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import io.renren.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("goodsService")
@Slf4j
public class GoodsServiceImpl extends ServiceImpl<GoodsDao, GoodsEntity> implements GoodsService {

    @Autowired
    private GoodsImageDao goodsImageDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private GoodsOptionDao goodsOptionDao;
    @Autowired
    private GoodsProductService goodsProductService;
    @Autowired
    private QuoteProductBaseInfoService quoteProductBaseInfoService;
    @Autowired
    private ProductBaseInfoService productBaseInfoService;
    @Autowired
    private GoodsAttributeService goodsAttributeService;
    @Autowired
    private GoodsImageService goodsImageService;
    @Autowired
    private GoodsTemplateService goodsTemplateService;
    @Autowired
    private GoodsCategoryService goodsCategoryService;
    @Autowired
    private GoodsCraftPriceService goodsCraftPriceService;
    @Autowired
    private QuoteAttributeOptionService quoteAttributeOptionService;
    @Autowired
    private QuoteFactoryMaterialService quoteFactoryMaterialService;
    @Autowired
    private GoodsMonitorService goodsMonitorService;
    @Autowired
    private FrozenGoodsService frozenGoodsService;
    @Autowired
    private UnitLibraryService unitLibraryService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private StoreGoodsCategoryTwdService storeGoodsCategoryTwdService;

    @Override
    // @DataSource(name = DataSourceNames.SECOND)
    public PageUtils queryPage(Map<String, Object> params) {
        String marketable = StringUtil.getRequestParamString(params.get("marketable"));
        String goodsType = StringUtil.getRequestParamString(params.get("goodsType"));
        Integer goodsId = StringUtil.getRequestParamInteger(params.get("goodsId"));
        Integer categoryId = StringUtil.getRequestParamInteger(params.get("categoryId"));
        String name = StringUtil.getRequestParamString(params.get("name"));
        Integer sellerId = StringUtil.getRequestParamInteger(params.get("sellerId"));
        Integer self = StringUtil.getRequestParamInteger(params.get("self"));
        Integer opMark = StringUtil.getRequestParamInteger(params.get("opMark"));
        Integer hide = StringUtil.getRequestParamInteger(params.get("hide"));
        Integer examineStatus = StringUtil.getRequestParamInteger(params.get("examineStatus"));
        Integer stageType = StringUtil.getRequestParamInteger(params.get("stageType"));
        Page<GoodsEntity> page = this.selectPage(new Query<GoodsEntity>(params).getPage(),
                new EntityWrapper<GoodsEntity>()
                        .eq("disabled", false)
                        .eq(StringUtils.isNotBlank(goodsType), "goods_type", goodsType)
                        .like(StringUtils.isNotBlank(name), "name", name)
                        .eq(goodsId != null, "goods_id", goodsId)
                        .eq(categoryId != null, "category_id", categoryId)
                        .eq(StringUtils.isNotBlank(marketable), "marketable", marketable)
                        .eq(sellerId != null, "seller_id", sellerId)
                        .eq(self != null, "self", self)
                        .eq(opMark != null, "op_mark", opMark)
                        .eq(hide != null, "hide_flag", hide)
                        .eq(examineStatus != null, "examine_status", examineStatus)
                        .eq(stageType != null, "stage_type", stageType)
                        .orderBy("goods_id", false));
        return new PageUtils(page);
    }

    @Override
    // @DataSource(name = DataSourceNames.SECOND)
    public PageUtils queryPageNew(Map<String, Object> params) {
//		List<Integer> parentCategoryIds = new ArrayList<>();
//		for(int i = 0;i<goodsCategoryEntities.size();i++){
//			parentCategoryIds.add(goodsCategoryEntities.get(i).getCategoryId());
//		}
//		List<Integer> categoryIds = goodsCategoryService.getCategoryIdsByParentIds(parentCategoryIds);
        Integer spu = StringUtil.getRequestParamInteger(params.get("spu"));
        String name = StringUtil.getRequestParamString(params.get("name"));
        Long userId = (Long) params.get("userId");
//		params.put("goods_type", "design_service：设计商品");
        Page<GoodsEntity> page = this.selectPage(new Query<GoodsEntity>(params).getPage(),
                new EntityWrapper<GoodsEntity>().eq(spu != null, "goods_id", spu)
                        .like(StringUtils.isNotBlank(name), "name", name)
//						.in("category_id",categoryIds)
                        .eq("seller_id", userId)
                        .eq("goods_type", "design")
        );

        return new PageUtils(page);
    }

    @Override
    // @DataSource(name = DataSourceNames.SECOND)
    @Transactional(rollbackFor = Exception.class)
    public void addDesign(Integer goodId, Integer designId) {
        goodsDao.addDesign(goodId, designId);
        //通知mq goodsId
        loadGoodsCacheEvent(Long.valueOf(goodId));
    }


    @Override
    // @DataSource(name = DataSourceNames.SECOND)
    public R getAllGoodsProperty(Long goodsId, Integer sellerId) {
        GoodsEntity goodsProperty = goodsDao.getAllGoodsProperty(goodsId);
        // GoodsEntity goods = goodsService.selectById(goodsId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("goods_id", goodsId);
        map.put("disabled", 0);
        // 获得并处理产品数据
        List<GoodsProductEntity> goodsProductList = getAndHandlerProducts(goodsProperty, map);
        if (goodsProductList.size() > 0) {
            goodsProductService.setCraftValues(goodsProperty, goodsProductList.get(0));
        }
        // 关联设计服务
        GoodsEntity designGood = null;
        if (org.apache.commons.lang3.StringUtils.isNotBlank(goodsProperty.getRelateDesignIds())) {
            designGood = this.selectById(goodsProperty.getRelateDesignIds());
        }
        // //默认图片和详细图片处理返回
        List<GoodsImageEntity> imageList = null;
        if (org.apache.commons.lang3.StringUtils.isNotBlank(goodsProperty.getImageUrls())) {
            imageList = goodsImageService.selectImageEntity(goodsProperty.getImageUrls());
        }
        List<GoodsImageEntity> infoList = null;
        if (org.apache.commons.lang3.StringUtils.isNotBlank(goodsProperty.getInfoUrls())) {
            infoList = goodsImageService.selectImageEntity(goodsProperty.getInfoUrls());
        }
        GoodsImageEntity videoEntity = null;
        if (org.apache.commons.lang3.StringUtils.isNotBlank(goodsProperty.getVideoUrl())) {
            videoEntity = goodsImageService.selectById(goodsProperty.getVideoUrl());
        }
        GoodsTemplateEntity goodsTemplateEntity = null;
        if (!(goodsProperty.getGoodsType().equals("fast") || goodsProperty.getGoodsType().equals("print"))) {
            goodsTemplateEntity = goodsTemplateService.getTemplateByCatId(goodsProperty.getCategoryId());
        }
        //获得单位库数据
        Map<String, Object> unitMap = New.hashMap();
        map.put("del_flag", 0);
        List<UnitLibraryEntity> unitLibraryList = unitLibraryService.selectByMap(unitMap);
        //获得原规格属性选项数据
        Map<String, Object> attributeAndCraftData = null;
        List<Map> allQuoteTemplate = null;
        //只有新商品且不为商务印刷和数码快印的允许查看规格
        if (!("fast".equals(goodsProperty.getGoodsType()) || "print".equals(goodsProperty.getGoodsType())) && !goodsProperty.getDateFlag()) {
            attributeAndCraftData = this.getAttributeAndCraftData(goodsProperty);
        } else if ("fast".equals(goodsProperty.getGoodsType()) || "print".equals(goodsProperty.getGoodsType())) {
            Integer factoryId = goodsProperty.getSellerId();
            allQuoteTemplate = quoteProductBaseInfoService.getQuoteAttributeInfo(goodsId, factoryId);
        }
        return R.ok().put("goods", goodsProperty).put("goodsProductList", goodsProductList)
                .put("designGood", designGood).put("imageList", imageList).put("infoList", infoList)
                .put("videoEntity", videoEntity).put("attributeAndCraftData", attributeAndCraftData)
                .put("allQuoteTemplate", allQuoteTemplate).put("goodsTemplateEntity", goodsTemplateEntity)
                .put("unitLibraryList", unitLibraryList);
    }

    @Override
    // @DataSource(name = DataSourceNames.SECOND)
    public Page<GoodsEntity> queryGoodsPage(Page<GoodsEntity> page, Map<String, Object> params) {
        return page.setRecords(this.baseMapper.selectGoodsList(page, params));
    }

    @Override
    // @DataSource(name = DataSourceNames.SECOND)
    public List<GoodsEntity> getGoodsByIds(String relateDesignIds) {
        List<GoodsEntity> goodsList = goodsDao.getGoodsByIds(relateDesignIds);
        return goodsList;
    }

    /**
     * 商品发布提交
     *
     * @param goods
     */
    @Override
    // @DataSource(name = DataSourceNames.SECOND)
    @Transactional(rollbackFor = Exception.class)
    public void pushGood(GoodsEntity goods) {
        // 保存商品
        // goods.setCreateTime(new Date());
        // goods.setCreateName(UserUtils.getCurentUser().getUsername());
        goods.setGoodsNo(builderGoodsBn(goods.getCategoryId()));
        goodsDao.insert(goods);
        Long goodsId = goods.getGoodsId();
        List<String> delImageIds = goods.getDelImageIds();
        String delImages = org.apache.commons.lang3.StringUtils.join(delImageIds, ",");
        List<Integer> list = changeStr2List(delImages);
        if (list != null && list.size() > 0) {
            goodsImageDao.fagDelImageByIds(list);
        }
//        if (delImageIds != null && delImageIds.size() > 0) {
//            goodsImageDao.fagDelImageByIds(StringUtils.join(delImageIds, ","));
//        }
		/*GoodsTemplateEntity template= goodsTemplateService.getTemplateByCatId(goods.getCategoryId());
		String optionJson = template.getOptionJson();
		long influenceSkuTotalPrice1 = template.getInfluenceSkuTotalPrice();
		net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(optionJson);
		List<Integer> countOptionIds = new ArrayList<>();
		for(int i = 0;i<jsonArray.size();i++){
			net.sf.json.JSONObject jsonObject = jsonArray.getJSONObject(i);
			String attributeId = jsonObject.getString("attributeId");
			if(influenceSkuTotalPrice1 == Integer.parseInt(attributeId)){
				countOptionIds = jsonObject.getJSONArray("optionId");
			}
		}*/
        // 给默认图片添加goodsId
        if (imageVerify(goods.getImageUrls())) {
            goodsImageService.newImageUpdate(goodsId,changeStr2List(goods.getImageUrls()));
//            goodsImageDao.updateImageByGoodsId(goodsId, goods.getImageUrls());
        }
        // 给详细图片添加goodsId
        if (imageVerify(goods.getInfoUrls())) {
            goodsImageService.newImageUpdate(goodsId,changeStr2List(goods.getInfoUrls()));
//            goodsImageDao.updateImageByGoodsId(goodsId, goods.getInfoUrls());
        }
        // 给视频添加goodsId
        if (imageVerify(goods.getVideoUrl())) {
            goodsImageService.newImageUpdate(goodsId,changeStr2List(goods.getVideoUrl()));
//            goodsImageDao.updateImageByGoodsId(goodsId, goods.getVideoUrl());
        }
        String good = JSONObject.toJSONString(goods);
        JSONObject jsonObject = JSON.parseObject(good);
        JSONArray itemList = jsonObject.getJSONArray("itemList");
        // 放单价的集合
        List<BigDecimal> singlePriceList = new ArrayList();
        // 遍历itemList集合,创建goodsProductList;
        // 定义标记变量,判断是否需要计算默认sku
        Boolean defaultSku = true;
        List<GoodsProductEntity> productList = new ArrayList<>();
        //定义默认sku的optionIds和craftIds,用以向product_base_info插入记录设置默认使用
        String defaultOptionIds = null;
        String defaultCraftOptionIds = null;
        for (int i = 0; i < itemList.size(); i++) {
            String marketable = itemList.getJSONObject(i).getString("marketable");
            if ("delete".equals(marketable)) {
                continue;
            }
            // 先判断用户是否自定义了默认sku
            GoodsProductEntity goodsProduct = new GoodsProductEntity();
            String defaultProduct = itemList.getJSONObject(i).getString("defaultProduct");

            goodsProduct.setGoodsId(goodsId);
            goodsProduct.setProductNo(builderGoodsBn(goods.getCategoryId()));
            goodsProduct.setCreateName(goods.getCreateName());
            // 设置规格属性集
            String options = setOptionIds(goods, itemList, i);
            goodsProduct.setOptionIds(options);
            //设置product_info
            String productInfo = goodsOptionDao.getOptionNamesByOptionIds(options);
            goodsProduct.setProductInfo(productInfo);
            //设置工艺
            StringBuffer craftBuffer = new StringBuffer();
            JSONArray cra = itemList.getJSONObject(i).getJSONArray("cra");
            setProductCraft(craftBuffer, cra);
            if (defaultProduct.equals("true")) {
                // 用户已经设置过默认sku
                defaultSku = false;
                goodsProduct.setDefaultProduct(true);
                defaultOptionIds = goodsProduct.getOptionIds();
                defaultCraftOptionIds = goodsProduct.getCraftOptionIds();
            } else {
                goodsProduct.setDefaultProduct(false);
            }
            goodsProduct.setCraftOptionIds(craftBuffer.toString());
            // 设置sku相关属性store/weight/totalPrice/marketPrice
            Map<String, BigDecimal> stringBigDecimalMap = setSkuNum(itemList, i, goodsProduct, goods);
//			BigDecimal productTotalPrice =
            // 计算单价
            // 判断该产品的规格属性是否含数字计价属性
//			Integer counter = goodsOptionDao.getCounterPrice(options);
            // -------------------算价方式二
            GoodsOptionEntity counterPriceNew = goodsOptionDao.getCounterPriceNew(options, goodsId);
            Integer counter = null;
            if (counterPriceNew != null) {
                counter = Integer.parseInt(counterPriceNew.getOptionValue());
            }
            //复印纸不算单价,箱价就是它的单价
            if (!"copy".equals(goods.getGoodsType())) {
                if (counter != null) {
                    if (goods.getStageType() == 0) {
                        //算两个平台的价格
                        BigDecimal productTotalPrice = stringBigDecimalMap.get("productTotalPrice");
                        BigDecimal singlePrice = productTotalPrice.divide(new BigDecimal(counter), 2, BigDecimal.ROUND_DOWN);
                        //设置单价
                        goodsProduct.setSinglePrice(singlePrice);
                        BigDecimal productTotalPricePop = stringBigDecimalMap.get("productTotalPricePop");
                        BigDecimal setSinglePricePop = productTotalPricePop.divide(new BigDecimal(counter), 2, BigDecimal.ROUND_DOWN);
                        //设置单价
                        goodsProduct.setSinglePricePop(setSinglePricePop);
//						singlePriceList.add(setSinglePricePop);
                        //若两个平台都有,则以紫云网的价格为主
                        singlePriceList.add(singlePrice);
                    } else if (goods.getStageType() == 1) {
                        //只算紫云网
                        BigDecimal productTotalPrice = stringBigDecimalMap.get("productTotalPrice");
                        BigDecimal singlePrice = productTotalPrice.divide(new BigDecimal(counter), 2, BigDecimal.ROUND_DOWN);
                        //设置单价
                        goodsProduct.setSinglePrice(singlePrice);
                        singlePriceList.add(singlePrice);
                    } else if (goods.getStageType() == 2) {
                        //只算pop平台
                        BigDecimal productTotalPricePop = stringBigDecimalMap.get("productTotalPricePop");
                        BigDecimal setSinglePricePop = productTotalPricePop.divide(new BigDecimal(counter), 2, BigDecimal.ROUND_DOWN);
                        //设置单价
                        goodsProduct.setSinglePricePop(setSinglePricePop);
                        singlePriceList.add(setSinglePricePop);
                    }
                } else {
                    // 若counter为空,则取原价格进集合
//                    singlePriceList.add(productTotalPrice);
                    if (goods.getStageType() == 0 || goods.getStageType() == 1) {
                        BigDecimal productTotalPrice = stringBigDecimalMap.get("productTotalPrice");
                        singlePriceList.add(productTotalPrice);
                    } else if (goods.getStageType() == 2) {
                        BigDecimal productTotalPricePop = stringBigDecimalMap.get("productTotalPricePop");
                        singlePriceList.add(productTotalPricePop);
                    }
                }
            } else {
                //将复印纸的箱价放入singlePriceList
                if (goods.getStageType() == 0 || goods.getStageType() == 1) {
                    BigDecimal expandPrice = goodsProduct.getExpandPrice();
                    singlePriceList.add(expandPrice);
                } else if (goods.getStageType() == 2) {
                    BigDecimal expandPricePop = goodsProduct.getExpandPricePop();
                    singlePriceList.add(expandPricePop);
                }
            }
            // 将产品放入商品集容器
            productList.add(goodsProduct);
        }
        // 设置默认sku  //defaultOptionIds  defaultCraftOptionIds
        if (defaultSku) {
            // 设置默认sku,保存产品
            Map<String, String> map = setDefaultSku(singlePriceList, productList, defaultOptionIds, defaultCraftOptionIds, goods);
            defaultOptionIds = map.get("defaultOptionIds");
            defaultCraftOptionIds = map.get("defaultCraftOptionIds");
        }
		/*
				//含工艺的规格
		String str = null;
		for (GoodsProductEntity productEntity:productList) {
			if(productEntity.getDefaultProduct()){
				//取出他的规格ids
				str = productEntity.getOptionIds();
			}
		}
		//设置完默认sku之后向工艺spu关联表插入一条新的数据记录
		List<Map<String, Object>> joinSkuOpionIds = goods.getJoinSkuOptionIds();
		if(joinSkuOpionIds != null){
			ArrayList<ProductBaseInfoEntity> productBaseInfoList = new ArrayList<>();
			for (Map map :joinSkuOpionIds) {
				Integer attribute = (Integer) map.get("attribute");
				List<Integer> option = (List<Integer>) map.get("option");
				for(int j = 0;j<option.size();j++){
					//工艺参与sku生成关联关系
					ProductBaseInfoEntity productBaseInfoEntity = new ProductBaseInfoEntity();
					productBaseInfoEntity.setGoodsId(goodsId);
					productBaseInfoEntity.setPartsId(0);
					productBaseInfoEntity.setAttributeId(attribute);
					productBaseInfoEntity.setOptionId(option.get(j));
					if(str.contains(option.get(j).toString())){
						//设置默认
						productBaseInfoEntity.setWhetherDefault(1);
					}
					productBaseInfoEntity.setCreateUser(goods.getCreateName());
					productBaseInfoList.add(productBaseInfoEntity);
				}
			}
			//插入参与sku生成工艺记录
			productBaseInfoService.insertBatch(productBaseInfoList);
		}*/
        // 循环生成sku
        goodsProductService.insertBatch(productList);
        //介入任务,变换sku向product_base_info插入记录-->defaultOptionIds defaultCraftOptionIds
        ArrayList<ProductBaseInfoEntity> productBaseInfoList = new ArrayList<>();
        handleDateToProductBaseInfoList(goods, jsonObject, defaultOptionIds, defaultCraftOptionIds, productBaseInfoList);
        //算价影响插入
        //下列方法已经暂时被推翻
		/*//第一步,获得模板下影响sku算价的规格id
		List<GoodsAttributeEntity> countAttributeList = goodsAttributeService.getCountAttributeByCategoryId(goods.getCategoryId());
		GoodsAttributeEntity countAttribute = null;
		if(countAttributeList.size() != 0){
			countAttribute = countAttributeList.get(0);
		}
//		GoodsAttributeEntity countAttribute = countAttributeList.get(0);
		//第二步,获得模板下用户选择的影响工艺算价的规格id
		String influenceCraftIds = goodsTemplateService.getInfluenceCraftIds(goods.getCategoryId());
		List<Integer> list = new ArrayList<>();
		if(StringUtils.isNotBlank(influenceCraftIds)){
			String[] split = influenceCraftIds.split(",");
			for(int i = 0;i<split.length;i++){
				list.add(Integer.parseInt(split[i]));
			}
		}
		//第三步,sku_price字段填充的规格id,single_craft字段填充的规格id
		for(int i = 0;i<ProductBaseInfoList.size();i++){
			if(StringUtils.isNotBlank(influenceCraftIds)){
				if(list.indexOf(ProductBaseInfoList.get(i).getAttributeId()) != -1){
					ProductBaseInfoList.get(i).setInfluenceCraftType("single_craft");
				}else{
					ProductBaseInfoList.get(i).setInfluenceCraftType("none");
				}
			}else{
				ProductBaseInfoList.get(i).setInfluenceCraftType("none");
			}
			//设置sku_price
			if(countAttribute != null){
				if(ProductBaseInfoList.get(i).getAttributeId().intValue() == countAttribute.getAttributeId().longValue()){
//			if(ProductBaseInfoList.get(i).getAttributeId().equals(countAttribute.getAttributeId())){
					ProductBaseInfoList.get(i).setInfluenceCraftType("sku_price");
				}
			}
		}*/
        //新的算价影响方式
        //根据分类取出模板表里的那个影响算价的id
        GoodsTemplateEntity templateByCat = goodsTemplateService.getTemplateByCatId(goods.getCategoryId());
        long influenceSkuTotalPrice = templateByCat.getInfluenceSkuTotalPrice();
        for (int i = 0; i < productBaseInfoList.size(); i++) {
            if (influenceSkuTotalPrice != 0) {
                if (productBaseInfoList.get(i).getAttributeId() == influenceSkuTotalPrice) {
                    productBaseInfoList.get(i).setInfluenceCraftType("sku_price");
                } else {
                    productBaseInfoList.get(i).setInfluenceCraftType("none");
                }
            } else {
                productBaseInfoList.get(i).setInfluenceCraftType("none");
            }
        }
        productBaseInfoService.insertBatch(productBaseInfoList);
        //通知mq goodsId
//		loadGoodsCacheEvent(goodsId);
    }

    /**
     * 介入任务的处理方法,标品生成规格记录插入productBaseInfo
     *
     * @param goods
     * @param jsonObject
     * @param defaultOptionIds
     * @param defaultCraftOptionIds
     * @param productBaseInfoList
     */
    private void handleDateToProductBaseInfoList(GoodsEntity goods, JSONObject jsonObject, String defaultOptionIds, String defaultCraftOptionIds, ArrayList<ProductBaseInfoEntity> productBaseInfoList) {
        Long goodsId = goods.getGoodsId();
        Integer categoryId = goods.getCategoryId();
        String createName = goods.getCreateName();
        JSONArray specificationItems = jsonObject.getJSONArray("specificationItems");
        //生成规格记录
        for (int i = 0; i < specificationItems.size(); i++) {
            specToProductBaseInfoList(defaultOptionIds, productBaseInfoList, goodsId, createName, specificationItems, i, categoryId);
        }
        //生成工艺记录
        JSONArray craftAttributes = jsonObject.getJSONArray("craftAttributes");
        if (craftAttributes.size() != 0) {
            for (int i = 0; i < craftAttributes.size(); i++) {
                specToProductBaseInfoList(null, productBaseInfoList, goodsId, createName, craftAttributes, i, categoryId);
            }
        }
    }

    /**
     * 将
     *
     * @param defaultOptionIds
     * @param productBaseInfoList
     * @param goodsId
     * @param createName
     * @param specificationItems
     * @param i
     */
    private void specToProductBaseInfoList(String defaultOptionIds, ArrayList<ProductBaseInfoEntity> productBaseInfoList, Long goodsId, String createName, JSONArray specificationItems, int i, int categoryId) {
        JSONObject attribute = specificationItems.getJSONObject(i);
        JSONObject attributeData = attribute.getJSONObject("attribute");
        String attributeId = attributeData.getString("attributeId");
        JSONArray options = attribute.getJSONArray("option");
        for (int j = 0; j < options.size(); j++) {
            JSONObject option = options.getJSONObject(j);
            String optionId = option.getString("optionId");
            ProductBaseInfoEntity productBaseInfoEntity = new ProductBaseInfoEntity();
            setProductBaseInfo(goodsId, createName, defaultOptionIds, attributeId, optionId, productBaseInfoEntity, categoryId);
            productBaseInfoList.add(productBaseInfoEntity);
        }
    }

    /**
     * 封装好productBaseInfo数据实体
     *
     * @param goodsId
     * @param defaultOptionIds
     * @param attributeId
     * @param optionId
     * @param productBaseInfoEntity
     */
    private void setProductBaseInfo(Long goodsId, String createName, String defaultOptionIds, String attributeId, String optionId, ProductBaseInfoEntity productBaseInfoEntity, int categoryId) {
        productBaseInfoEntity.setGoodsId(goodsId);
        productBaseInfoEntity.setPartsId(0);
        productBaseInfoEntity.setCategoryId(categoryId);
        productBaseInfoEntity.setAttributeId(Integer.parseInt(attributeId));
        productBaseInfoEntity.setOptionId(Integer.parseInt(optionId));
        productBaseInfoEntity.setCreateUser(createName);
        if (defaultOptionIds != null) {
            if (defaultOptionIds.indexOf(optionId) != -1) {
                //默认sku的选项中,包含这个选择值
                productBaseInfoEntity.setWhetherDefault(1);
            } else {
                productBaseInfoEntity.setWhetherDefault(0);
            }
        }
    }

    private void setProductCraft(StringBuffer craftBuffer, JSONArray cra) {
        for (int j = 0; j < cra.size(); j++) {
            JSONArray option = cra.getJSONObject(j).getJSONArray("option");
            for (int k = 0; k < option.size(); k++) {
                String optionId = option.getJSONObject(k).getString("optionId");
                craftBuffer.append(optionId);
                craftBuffer.append(",");
            }
        }
    }

    /**
     * 编辑更新商品
     *
     * @param goods
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
//    @OptionGoodsMonitoring
    public void updateGoods(GoodsEntity goods, Long userId) {
        //开始商品编辑记录
        GoodsEntity oldGoods = goodsProductService.getGoodsAndProduct(goods.getGoodsId());
        Map<String, String> monitor = New.hashMap();
        try {
            monitor = GoodsMonitorUtils.monitor(oldGoods, goods, monitor);
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            monitor.put("日志记录出现异常", sw.toString() + "\r\n");
        }
        if (monitor != null && monitor.size() > 0) {
            GoodsMonitorEntity goodsMonitorEntity = new GoodsMonitorEntity();
            if (UserUtils.getCurentUser() != null) {
                goodsMonitorEntity.setSource("erp");
            } else {
                goodsMonitorEntity.setSource("pop");
            }
            goodsMonitorEntity.setCreateId(userId);
            goodsMonitorEntity.setMessage(JsonUtils.object2String(monitor));
            goodsMonitorEntity.setSdbId(goods.getGoodsId().toString());
            goodsMonitorEntity.setType("Goods");
            goodsMonitorService.insert(goodsMonitorEntity);
        }
        //结束商品编辑记录
        // 按集合删除图片
        List<String> delImageIds = goods.getDelImageIds();
        String delImages = org.apache.commons.lang3.StringUtils.join(delImageIds, ",");
        List<Integer> list = changeStr2List(delImages);
        if (list != null && list.size() > 0) {
            goodsImageDao.fagDelImageByIds(list);
        }
//        if (StringUtils.isNotBlank(delImages)) {
//            goodsImageDao.fagDelImageByIds(delImages);
//        }
        // 更新商品
        goodsDao.updateById(goods);
        //保存图片relationId
        // 给默认图片添加goodsId
        if (imageVerify(goods.getImageUrls())) {
//            goodsImageDao.updateImageByGoodsId(goods.getGoodsId(), goods.getImageUrls());
            goodsImageService.newImageUpdate(goods.getGoodsId(),changeStr2List(goods.getImageUrls()));
        }
        // 给详细图片添加goodsId
        if (imageVerify(goods.getInfoUrls())) {
//            goodsImageDao.updateImageByGoodsId(goods.getGoodsId(), goods.getInfoUrls());
            goodsImageService.newImageUpdate(goods.getGoodsId(),changeStr2List(goods.getInfoUrls()));
        }
        // 给视频添加goodsId
        if (imageVerify(goods.getVideoUrl())) {
//            goodsImageDao.updateImageByGoodsId(goods.getGoodsId(), goods.getVideoUrl());
            goodsImageService.newImageUpdate(goods.getGoodsId(),changeStr2List(goods.getVideoUrl()));
        }
        Long goodsId = goods.getGoodsId();
        // 更新产品信息
        List<GoodsProductEntity> goodsProductList = goods.getGoodsProductList();
        // 修改单价
        for (int i = 0; i < goodsProductList.size(); i++) {
            List<GoodsOptionEntity> goodsOptionList = goodsProductList.get(i).getGoodsOptionList();
            List<Long> optionIds = new ArrayList<>();
            for (int j = 0; j < goodsOptionList.size(); j++) {
                Long optionId = goodsOptionList.get(j).getOptionId();
                optionIds.add(optionId);
            }
            String options = StringUtils.join(optionIds, ",");

//			Integer counterPrice = goodsOptionDao.getCounterPrice(options);
            GoodsOptionEntity counterPriceNew = goodsOptionDao.getCounterPriceNew(options, goodsId);
            Integer counterPrice = null;
            if (counterPriceNew != null) {
                counterPrice = Integer.parseInt(counterPriceNew.getOptionValue());
            }
            if (!"copy".equals(goods.getGoodsType())) {
                if (counterPrice != null) {
                    // 需要算单价
                    if (goods.getStageType() == 0) {
                        //设置两种单价
                        //设置紫云单价
                        BigDecimal totalPrice = goodsProductList.get(i).getTotalPrice();
                        BigDecimal singlePrice = totalPrice.divide(new BigDecimal(counterPrice), 2, BigDecimal.ROUND_DOWN);
                        goodsProductList.get(i).setSinglePrice(singlePrice);
                        //设置pop单价
                        BigDecimal totalPricePop = goodsProductList.get(i).getTotalPricePop();
                        BigDecimal singlePricePop = totalPricePop.divide(new BigDecimal(counterPrice), 2, BigDecimal.ROUND_DOWN);
                        goodsProductList.get(i).setSinglePricePop(singlePricePop);
                    } else if (goods.getStageType() == 1) {
                        //设置紫云单价
                        BigDecimal totalPrice = goodsProductList.get(i).getTotalPrice();
                        BigDecimal singlePrice = totalPrice.divide(new BigDecimal(counterPrice), 2, BigDecimal.ROUND_DOWN);
                        goodsProductList.get(i).setSinglePrice(singlePrice);
                    } else if (goods.getStageType() == 2) {
                        //设置pop单价
                        BigDecimal totalPricePop = goodsProductList.get(i).getTotalPricePop();
                        BigDecimal singlePricePop = totalPricePop.divide(new BigDecimal(counterPrice), 2, BigDecimal.ROUND_DOWN);
                        goodsProductList.get(i).setSinglePricePop(singlePricePop);
                    }
                }
            } else {
                //复印纸需要算箱价
                calculateCopyPrice(goodsProductList.get(i), goods, goodsProductList.get(i).getTotalPrice(), goodsProductList.get(i).getTotalPricePop());
            }
        }
        goodsProductService.updateBatchById(goodsProductList);
        //生成新的sku
        JSONObject jsonObject = JSON.parseObject(JSONObject.toJSONString(goods));
        JSONArray itemList = jsonObject.getJSONArray("itemList");
        List<GoodsProductEntity> addProductList = new ArrayList<>();
        for (int i = 0; i < itemList.size(); i++) {
            String marketable = itemList.getJSONObject(i).getString("marketable");
            if ("delete".equals(marketable)) {
                continue;
            }
            GoodsProductEntity productEntity = new GoodsProductEntity();
            productEntity.setGoodsId(goods.getGoodsId());
            productEntity.setProductNo(builderGoodsBn(goods.getCategoryId()));
            productEntity.setCreateName(goods.getCreateName());
//			// 设置规格属性集
            String options = setOptionIds(goods, itemList, i);
            productEntity.setOptionIds(options);
            //设置product_info
            String productInfo = goodsOptionDao.getOptionNamesByOptionIds(options);
            productEntity.setProductInfo(productInfo);
            //设置工艺
            StringBuffer craftBuffer = new StringBuffer();
            JSONArray cra = itemList.getJSONObject(i).getJSONArray("cra");
            setProductCraft(craftBuffer, cra);
            productEntity.setCraftOptionIds(craftBuffer.toString());
            // 设置sku相关属性store/weight/totalPrice/marketPrice
            Map<String, BigDecimal> stringBigDecimalMap = setSkuNum(itemList, i, productEntity, goods);
            //复印纸不算单价
            if (!"copy".equals(goods.getGoodsType())) {
//                Integer counter = goodsOptionDao.getCounterPrice(options);
                GoodsOptionEntity counterPriceNew = goodsOptionDao.getCounterPriceNew(options, goodsId);
                Integer counter = null;
                if (counterPriceNew != null) {
                    counter = Integer.parseInt(counterPriceNew.getOptionValue());
                }
                // -------------------算价方式二
                // Integer counter = goodsOptionDao.getCounterPriceNew(options);
                if (counter != null) {
                    if (goods.getStageType() == 0) {
                        //算两种单价
                        //算紫云网单价
                        BigDecimal productTotalPrice = stringBigDecimalMap.get("productTotalPrice");
                        BigDecimal singlePrice = productTotalPrice.divide(new BigDecimal(counter), 2, BigDecimal.ROUND_DOWN);
                        //设置单价
                        productEntity.setSinglePrice(singlePrice);
                        //算pop平台单价
                        BigDecimal productTotalPricePop = stringBigDecimalMap.get("productTotalPricePop");
                        BigDecimal singlePricePop = productTotalPricePop.divide(new BigDecimal(counter), 2, BigDecimal.ROUND_DOWN);
                        //设置单价
                        productEntity.setSinglePricePop(singlePricePop);
                    } else if (goods.getStageType() == 1) {
                        //算紫云网单价
                        BigDecimal productTotalPrice = stringBigDecimalMap.get("productTotalPrice");
                        BigDecimal singlePrice = productTotalPrice.divide(new BigDecimal(counter), 2, BigDecimal.ROUND_DOWN);
                        //设置单价
                        productEntity.setSinglePrice(singlePrice);
                    } else if (goods.getStageType() == 2) {
                        //算pop平台单价
                        BigDecimal productTotalPricePop = stringBigDecimalMap.get("productTotalPricePop");
                        BigDecimal singlePricePop = productTotalPricePop.divide(new BigDecimal(counter), 2, BigDecimal.ROUND_DOWN);
                        //设置单价
                        productEntity.setSinglePricePop(singlePricePop);
                    }
                }//如果算价单位,则跳过
            }
            addProductList.add(productEntity);
        }
        if (addProductList.size() != 0) {
            goodsProductService.insertBatch(addProductList);
        }
        //-----------------------------新添加的商品向product_base_info插入相应的记录
        JSONArray addAttributeData = jsonObject.getJSONArray("addAttributeData");

        Map<String, Object> map = New.hashMap();
        map.put("default_product", 1);
        map.put("goods_id", goods.getGoodsId());
        List<GoodsProductEntity> goodsProductEntityList = goodsProductService.selectByMap(map);
        if (addAttributeData != null && addAttributeData.size() != 0) {
            //介入任务,变换sku向product_base_info插入记录-->defaultOptionIds defaultCraftOptionIds
            ArrayList<ProductBaseInfoEntity> productBaseInfoList = new ArrayList<>();
//		handleDateToProductBaseInfoList(goods, jsonObject, defaultOptionIds, defaultCraftOptionIds, ProductBaseInfoList);
//		productBaseInfoService.insertBatch(ProductBaseInfoList);
            //获得默认sku的option_ids和craft_option_ids

            if (goodsProductEntityList.size() == 1) {
                //默认商品有且只有一个
                String optionIds = goodsProductEntityList.get(0).getOptionIds();
                String craftOptionIds = goodsProductEntityList.get(0).getCraftOptionIds();
//			handleDateToProductBaseInfoList(goods, jsonObject, defaultOptionIds, defaultCraftOptionIds, ProductBaseInfoList);
                for (int i = 0; i < addAttributeData.size(); i++) {
                    specToProductBaseInfoList(optionIds, productBaseInfoList, goods.getGoodsId(), goods.getCreateName(), addAttributeData, i, goods.getCategoryId());
                }
            }
            //插入记录
            productBaseInfoService.insertBatch(productBaseInfoList);
        }
        //修改默认选项
        if (goodsProductEntityList.size() == 1) {
            GoodsProductEntity productEntity = goodsProductEntityList.get(0);
            String optionIds = productEntity.getOptionIds();
            String craftOptionIds = productEntity.getCraftOptionIds();
            List<Integer> defaultOptionIds = New.arrayList();
            if (StringUtils.isNotBlank(optionIds)) {
                String[] split = optionIds.split(",");
                if (split != null && split.length > 0) {
                    for (int i = 0; i < split.length; i++) {
                        defaultOptionIds.add(Integer.parseInt(split[i]));
                    }
                }
            }
            Map<String, Object> map4 = New.hashMap();
            map4.put("del_flag", 0);
            map4.put("goods_id", goods.getGoodsId());
            List<ProductBaseInfoEntity> productBaseInfoEntityList = productBaseInfoService.selectByMap(map4);
            GoodsTemplateEntity templateByCat = goodsTemplateService.getTemplateByCatId(goods.getCategoryId());
            long influenceSkuTotalPrice = templateByCat.getInfluenceSkuTotalPrice();
            for (int j = 0; j < productBaseInfoEntityList.size(); j++) {
                if (defaultOptionIds.contains(productBaseInfoEntityList.get(j).getOptionId())) {
                    //是默认
                    productBaseInfoEntityList.get(j).setWhetherDefault(1);
                } else {
                    productBaseInfoEntityList.get(j).setWhetherDefault(0);
                }
                //影响sku工艺价格改写
                if (influenceSkuTotalPrice != 0) {
                    if (productBaseInfoEntityList.get(j).getAttributeId() == influenceSkuTotalPrice) {
                        productBaseInfoEntityList.get(j).setInfluenceCraftType("sku_price");
                    } else {
                        productBaseInfoEntityList.get(j).setInfluenceCraftType("none");
                    }
                } else {
                    productBaseInfoEntityList.get(j).setInfluenceCraftType("none");
                }
            }
            productBaseInfoService.updateBatchById(productBaseInfoEntityList);
            //找到工艺,对工艺做修改了的操作一下
            if (StringUtils.isNotBlank(craftOptionIds)) {
                productBaseInfoService.solveEditCraft(goodsId, craftOptionIds);
            }
        }
        //通知mq goodsId
//		loadGoodsCacheEvent(goodsId);
    }

    /**
     * 更新spu状态
     *
     * @param goodsId
     * @param status
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(Long goodsId, String status, Long userId) {
        //开始商品编辑记录
        Map<String, String> monitor = New.hashMap();
        GoodsMonitorEntity goodsMonitorEntity = new GoodsMonitorEntity();
        goodsMonitorEntity.setCreateId(userId);
        goodsMonitorEntity.setMessage("更改商品状态为:" + status);
        goodsMonitorEntity.setSdbId(goodsId.toString());
        goodsMonitorEntity.setType("Goods");
        if(UserUtils.getCurentUser() != null){
            goodsMonitorEntity.setSource("erp");
        }else{
            goodsMonitorEntity.setSource("pop");
        }
        goodsMonitorService.insert(goodsMonitorEntity);
        //结束商品编辑记录
        goodsDao.updateStatus(goodsId, status);
//		loadGoodsCacheEvent(goodsId);
    }

    @Override
    public void loadGoodsCacheEvent(Long goodsId) {
        log.info(">>>>> 开始刷新单个缓存spu" + goodsId + " <<<<<");
        UpdateGoodsCacheEvent build = UpdateGoodsCacheEvent.builder().source(this).goodsId(goodsId).build();
        EventBusPusher.syncPost(build);
        log.info(">>>>> 结束更新spu <<<<<");
    }

    @Override
    public void loadAllGoodsCacheEvent() {
        log.info(">>>>> 开始缓存全部spu <<<<<");
        RefreshGoodsCacheEvent build = RefreshGoodsCacheEvent.builder().source(this).build();
        EventBusPusher.syncPost(build);
        log.info(">>>>> 结束更新 <<<<<");
    }

    /**
     * 规格属性相同的产品合并
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void solveBug() {
        List<Map<String, Object>> bugDate = this.baseMapper.getBugDate();
        List<GoodsProductEntity> goodsProductList = New.arrayList();
        for (int i = 0; i < bugDate.size(); i++) {
            Map<String, Object> map = bugDate.get(i);
            Map<String, Object> map1 = New.hashMap();
            Integer goodsId = ((BigInteger) map.get("goods_id")).intValue();
            String optionIds = (String) map.get("option_ids");
            String craftOptionIds = (String) map.get("craft_option_ids");
            map1.put("goods_id", goodsId);
            map1.put("option_ids", optionIds);
            List<GoodsProductEntity> goodsProductEntityList = goodsProductService.selectByMap(map1);
            Boolean mark = true;
            Boolean isDef = false;
            for (int j = 0; j < goodsProductEntityList.size(); j++) {
                if (goodsProductEntityList.get(j).getDefaultProduct()) {
                    isDef = true;
                }
            }
            for (int k = 0; k < goodsProductEntityList.size(); k++) {
                if (!isDef) {
                    goodsProductEntityList.get(k).setCraftOptionIds(craftOptionIds);
                    goodsProductList.add(goodsProductEntityList.get(k));
                    goodsProductEntityList.get(k).setDisabled(true);
                    if (mark) {
                        goodsProductEntityList.get(k).setDisabled(false);
                        mark = false;
                    }
                } else {
                    //该sku有默认的sku,不能删除
                    if (!goodsProductEntityList.get(k).getDefaultProduct()) {
                        goodsProductEntityList.get(k).setCraftOptionIds(craftOptionIds);
                        //删除
                        goodsProductEntityList.get(k).setDisabled(true);
                        goodsProductList.add(goodsProductEntityList.get(k));
                    } else {
                        goodsProductEntityList.get(k).setCraftOptionIds(craftOptionIds);
                        goodsProductList.add(goodsProductEntityList.get(k));
                        goodsProductEntityList.get(k).setDisabled(false);
                    }
                }
            }
        }
        goodsProductService.updateBatchById(goodsProductList);
    }

    /**
     * 校验工艺价格
     *
     * @param verifyPriceVo
     * @return
     */
    @Override
    public String verifyCraftPrice(VerifyPriceVo verifyPriceVo, Long sellerId) {
        List<AttributeVo> attributeVoList = verifyPriceVo.getAttributeVoList();
        Integer templateId = verifyPriceVo.getTemplateId();
        List<Integer> influenceCraftId = New.arrayList();
        if (attributeVoList != null && attributeVoList.size() > 0) {
            for (int i = 0; i < attributeVoList.size(); i++) {
                AttributeVo attributeVo = attributeVoList.get(i);
                Integer craftId = attributeVo.getCraftId();
                influenceCraftId.add(craftId);
                List<Integer> craftOptionIds = attributeVo.getCraftOptionIds();
                List<Integer> optionIds = attributeVo.getOptionIds();
                for (int ii = 0; ii < craftOptionIds.size(); ii++) {
                    for (int iii = 0; iii < optionIds.size(); iii++) {
                        //查询是否有该数据
                        Map<String, Object> map = New.hashMap();
                        map.put("option_id", craftOptionIds.get(ii));
                        map.put("influence_id", optionIds.get(iii));
                        map.put("template_id", templateId);
                        map.put("option_origin", "standard_craft");
                        map.put("seller_id", sellerId);
                        List<GoodsCraftPriceEntity> goodsCraftPriceEntities = goodsCraftPriceService.selectByMap(map);
                        log.info(" 校验工艺价格参数 " + map);
                        if (null == goodsCraftPriceEntities || goodsCraftPriceEntities.size() == 0) {
                            //如果有一条记录没有查到,则提示尚未配价
                            GoodsOptionEntity craftGoodsEntity = goodsOptionDao.selectById(craftOptionIds.get(ii));
                            GoodsOptionEntity attributeGoodsEntity = goodsOptionDao.selectById(optionIds.get(iii));
                            return "工艺选项:" + craftGoodsEntity.getOptionName() +
                                    ",影响该工艺价格规格选项:" + attributeGoodsEntity.getOptionName() + "尚未配价,请去工艺详情那配置价格";
                        }
                    }
                }
            }
        }
        //查询不被影响的单纯工艺是否有价格
//		List<Integer> craftIds = verifyPriceVo.getCraftIds();
        List<Integer> craftIds = verifyPriceVo.getAlwaysCraftOptions();
        if (craftIds != null && craftIds.size() > 0) {
            for (int j = 0; j < craftIds.size(); j++) {
//				if(influenceCraftId != null && influenceCraftId.size() > 0){
//					if(influenceCraftId.indexOf(craftIds.get(j)) != -1){
                //没有在哪出现
                Map<String, Object> map = New.hashMap();
                map.put("option_id", craftIds.get(j));
                map.put("template_id", templateId);
                map.put("seller_id", sellerId);
                List<GoodsCraftPriceEntity> goodsCraftPriceEntities = goodsCraftPriceService.selectByMap(map);
                if (null == goodsCraftPriceEntities || goodsCraftPriceEntities.size() == 0) {
                    //如果有一条记录没有查到,则提示尚未配价
                    GoodsOptionEntity craftGoodsEntity = goodsOptionDao.selectById(craftIds.get(j));
                    return "工艺选项:" + craftGoodsEntity.getOptionName() + "尚未配价,请去工艺详情那配置价格";
                }
//					}
//				}
            }
        }
//		Integer templateId = verifyPriceVo.getTemplateId();
//		GoodsTemplateEntity goodsTemplateEntity = goodsTemplateService.selectById(templateId);
//		String influenceCraftIds = goodsTemplateEntity.getInfluenceCraftIds();
//		JSONArray jSONArray = JSON.parseArray(influenceCraftIds);
//		//获得有效的规格工艺影响map,key是工艺,value是选项
//		Map<Integer, String> map = New.hashMap();
//		for(int i =0;i<jSONArray.size();i++){
//			JSONObject jsonObject = jSONArray.getJSONObject(i);
//			//[{"craftId":1388,"attributeIds":[]},{"craftId":1428,"attributeIds":[]}]
//			Integer craftId = Integer.parseInt(jsonObject.getString("craftId"));
////			String craftId = jsonObject.getString("craftId");
//			JSONArray attributeIds = jsonObject.getJSONArray("attributeIds");
//			if(attributeIds != null && attributeIds.size() >0){
//				//获得该规格下的所有选项
//				String optionIds = goodsOptionDao.selectByAttributeId(attributeIds.get(i));
//			}
//		}
//		List<List<Integer>> optionIdList = verifyPriceVo.getOptionIdList();
//		List<Integer> craftIds = verifyPriceVo.getCraftIds();
//		for(int k = 0;k<craftIds.size();k++ ){
//			String s = map.get(craftIds.get(k));
////			if(StringUtils.isNotBlank(s) && s.contains()){
////
////
////			}
//		}
        return "ok";
    }

    /**
     * 报价校验工艺价格
     *
     * @return
     */
    @Override
    public String quotePrice(String ids, Integer sellerId) {
        List<Integer> param = this.baseMapper.quotePriceCount(ids);
        List<Integer> result = this.baseMapper.quotePrice(ids, sellerId);
        //兼容脏数据
        if (param.size() <= result.size()) {
            return "ok";
        } else {
            List<Integer> noPriceCraftIds = New.arrayList();
            for (Integer optionId : param) {
                if (result.indexOf(optionId) == -1) {
                    noPriceCraftIds.add(optionId);
                }
            }
            StringBuffer stringBuffer = new StringBuffer();
            if (noPriceCraftIds != null && noPriceCraftIds.size() > 0) {
                List<QuoteAttributeOptionEntity> quoteAttributeOptionEntityList = quoteAttributeOptionService.selectBatchIds(noPriceCraftIds);
                if (quoteAttributeOptionEntityList != null && quoteAttributeOptionEntityList.size() > 0) {
                    for (QuoteAttributeOptionEntity quoteAttributeOptionEntity : quoteAttributeOptionEntityList) {
                        stringBuffer.append("工艺选项名:");
                        stringBuffer.append(quoteAttributeOptionEntity.getOptionName());
                        stringBuffer.append("工艺选项id");
                        stringBuffer.append(quoteAttributeOptionEntity.getId());
                        stringBuffer.append("没有找到工艺价格;  ");
                    }
                }
            }
            return stringBuffer.toString();
        }
    }

    /**
     * 商务印刷机器校验
     *
     * @param printPriceVo
     * @return
     */
    @Override
    public String verifyPrintPrice(PrintPriceVo printPriceVo, Integer factoryId) {
        //获得所有的印刷机机器价格
        List<VerifyPrintPriceDto> verifyPrintPriceDtoList = this.baseMapper.getVerifyPrintPriceDate(factoryId);
        //处理克重材料选项,将其分类为特种纸和非特种纸
        List<Integer> weightOptionIds = printPriceVo.getWeightOptionIds();
        List<Integer> colorOptionIds = printPriceVo.getColorOptionIds();
        List<Integer> sizeOptionIds = printPriceVo.getSizeOptionIds();
        //先校验这些材料是否存在切不为0
        String s = verifyMaterialPrice(weightOptionIds, factoryId);
        if (!s.equals("ok")) {
            return s;
        }
        //获得option_value
        List<QuoteAttributeOptionEntity> quoteAttributeOptionList = quoteAttributeOptionService.selectBatchIds(sizeOptionIds);
        List<QuoteAttributeOptionEntity> canUvWeightOptionValues = this.baseMapper.getUvType(StringUtils.join(weightOptionIds, ","), true);
        List<QuoteAttributeOptionEntity> notCanUvWeightOptionValues = this.baseMapper.getUvType(StringUtils.join(weightOptionIds, ","), false);

        for (int i = 0; i < colorOptionIds.size(); i++) {
            for (int ii = 0; ii < quoteAttributeOptionList.size(); ii++) {
                for (int iii = 0; iii < canUvWeightOptionValues.size(); iii++) {
                    Boolean flagA = true;
                    lableA:
                    for (int j = 0; j < verifyPrintPriceDtoList.size(); j++) {
                        Integer maxLength = verifyPrintPriceDtoList.get(j).getMaxLength();
                        Integer minLength = verifyPrintPriceDtoList.get(j).getMinLength();
                        Integer maxWide = verifyPrintPriceDtoList.get(j).getMaxWide();
                        Integer minWide = verifyPrintPriceDtoList.get(j).getMinWide();
                        Integer maxWeight = verifyPrintPriceDtoList.get(j).getMaxWeight();
                        Integer minWeight = verifyPrintPriceDtoList.get(j).getMinWeight();
                        Integer colorId = verifyPrintPriceDtoList.get(j).getId();
                        if (verifyPrintPriceDtoList.get(j).getCanUv()) {
                            //判断颜色是否相等,克重是否在克重范围内,尺寸是否在范围类
                            if (colorId.equals(colorOptionIds.get(i))) {
                                if (Integer.parseInt(canUvWeightOptionValues.get(iii).getOptionName2()) >= minWeight && Integer.parseInt(canUvWeightOptionValues.get(iii).getOptionName2()) <= maxWeight) {
                                    String optionValue = quoteAttributeOptionList.get(ii).getOptionValue();
                                    String[] split = optionValue.split(",");
                                    int length = Integer.parseInt(split[0]);
                                    int wide = Integer.parseInt(split[1]);
                                    if (length <= maxLength && wide <= maxWide) {
                                        flagA = false;
                                        break lableA;
                                    }
                                }
                            }
                        }
                    }
                    if (flagA) {
                        QuoteAttributeOptionEntity quoteAttributeOptionEntity = quoteAttributeOptionService.selectById(colorOptionIds.get(i));
                        return "颜色名:" + quoteAttributeOptionEntity.getOptionName() + "长和宽:" + quoteAttributeOptionList.get(ii).getOptionValue() + "材料类型:" + canUvWeightOptionValues.get(iii).getOptionName() + "克重:" + canUvWeightOptionValues.get(iii).getOptionName2();
                    }
                }
                for (int kkk = 0; kkk < notCanUvWeightOptionValues.size(); kkk++) {
                    Boolean flagB = true;
                    lableB:
                    for (int j = 0; j < verifyPrintPriceDtoList.size(); j++) {
                        Integer maxLength = verifyPrintPriceDtoList.get(j).getMaxLength();
                        Integer minLength = verifyPrintPriceDtoList.get(j).getMinLength();
                        Integer maxWide = verifyPrintPriceDtoList.get(j).getMaxWide();
                        Integer minWide = verifyPrintPriceDtoList.get(j).getMinWide();
                        Integer maxWeight = verifyPrintPriceDtoList.get(j).getMaxWeight();
                        Integer minWeight = verifyPrintPriceDtoList.get(j).getMinWeight();
                        Integer colorId = verifyPrintPriceDtoList.get(j).getId();
                        if (!verifyPrintPriceDtoList.get(j).getCanUv()) {
                            //判断颜色是否相等,克重是否在克重范围内,尺寸是否在范围类
                            if (colorId.equals(colorOptionIds.get(i))) {
                                if (Integer.parseInt(notCanUvWeightOptionValues.get(kkk).getOptionName2()) >= minWeight && Integer.parseInt(notCanUvWeightOptionValues.get(kkk).getOptionName2()) <= maxWeight) {
                                    String optionValue = quoteAttributeOptionList.get(ii).getOptionValue();
                                    String[] split = optionValue.split(",");
                                    int length = Integer.parseInt(split[0]);
                                    int wide = Integer.parseInt(split[1]);
                                    if (length <= maxLength && wide <= maxWide) {
                                        flagB = false;
                                        break lableB;
                                    }
                                }
                            }
                        }
                    }
                    if (flagB) {
                        QuoteAttributeOptionEntity quoteAttributeOptionEntity = quoteAttributeOptionService.selectById(colorOptionIds.get(i));
                        return "颜色id:" + quoteAttributeOptionEntity.getOptionName() + "长和宽:" + quoteAttributeOptionList.get(ii).getOptionValue() + "材料类型:" + notCanUvWeightOptionValues.get(kkk).getOptionName() + "克重:" + notCanUvWeightOptionValues.get(kkk).getOptionName2();
                    }
                }
            }
        }
        return "ok";
    }

    /**
     * 数码快印组合计价校验
     *
     * @param fastPriceVoList
     * @return
     */
    @Override
    public String verifyFastPrice(List<FastPriceVo> fastPriceVoList, Integer factoryId) {
        //先搜索出所有的组合计价
//		Integer factoryId = 1;
        List<VerifyFastPriceDto> verifyFastPriceDtoList = this.baseMapper.getAllGroupPrice(factoryId);
        //关键字:颜色,尺寸,材料,克重

        //校验分单部件校验和多部件校验
        if (fastPriceVoList != null && fastPriceVoList.size() == 1) {
            //单部件
            FastPriceVo fastPriceVo = fastPriceVoList.get(0);
            List<QuoteAttributeOptionEntity> size = this.baseMapper.getQuoteAttributeOptionByAttributeTypeValueFromOptionIds(StringUtils.join(fastPriceVo.getSelectedAttributeIds(), ","), "size");
            List<QuoteAttributeOptionEntity> colour = this.baseMapper.getQuoteAttributeOptionByAttributeTypeValueFromOptionIds(StringUtils.join(fastPriceVo.getSelectedAttributeIds(), ","), "colour");
            List<Integer> selectedMaterialIds = fastPriceVo.getSelectedMaterialIds();
            if (!(selectedMaterialIds != null && selectedMaterialIds.size() > 0)) {
                return "不允许材料为空";
            }
            //先校验这些材料是否存在切不为0
//			String s = verifyMaterialPrice(selectedMaterialIds,factoryId);
//			if(!s.equals("ok")){
//				return s;
//			}
            List<QuoteAttributeOptionEntity> materiaEntity = this.baseMapper.getQuoteAttributeOptionByAttributeTypeValueFromOptionIds(StringUtils.join(selectedMaterialIds, ","), "material");
            if (!(size != null && size.size() > 0)) {
                return "没有尺寸,无法匹配组合价格";
            }
            if (!(colour != null && colour.size() > 0)) {
                return "没有颜色,无法匹配组合价格";
            }
            if (!(selectedMaterialIds != null && selectedMaterialIds.size() > 0)) {
                return "没有克重,无法匹配组合价格";
            }
            //遍历尺寸选项
            for (int i = 0; i < size.size(); i++) {
                //遍历颜色选项
                for (int ii = 0; ii < colour.size(); ii++) {
                    //遍历克重选项
                    for (int iii = 0; iii < materiaEntity.size(); iii++) {
                        //遍历结果集,找匹配
                        Boolean flagB = true;
                        lableB:
                        for (int z = 0; z < verifyFastPriceDtoList.size(); z++) {
                            //获得颜色id
                            Integer colourId = verifyFastPriceDtoList.get(z).getColourId();
                            //获得材料克重id
                            Integer materialId = verifyFastPriceDtoList.get(z).getMaterialId();
                            //获得材料长
                            Integer paperLength = verifyFastPriceDtoList.get(z).getPaperLength();
                            //获得材料宽
                            Integer paperWide = verifyFastPriceDtoList.get(z).getPaperWide();
                            //获得机器最小克重
                            Integer minWeight = verifyFastPriceDtoList.get(z).getMinWeight();
                            //获得机器最大克重
                            Integer maxWeight = verifyFastPriceDtoList.get(z).getMaxWeight();
                            //获得机器最小长
                            Integer minLength = verifyFastPriceDtoList.get(z).getMinLength();
                            //获得机器最小宽
                            Integer minWide = verifyFastPriceDtoList.get(z).getMinWide();
                            //获得机器最大长
                            Integer maxLength = verifyFastPriceDtoList.get(z).getMaxLength();
                            //获得机器最大宽
                            Integer maxWide = verifyFastPriceDtoList.get(z).getMaxWide();
                            //先比较颜色和材料是否符合
                            if (colour.get(ii).getId().equals(colourId)) {
                                if (materiaEntity.get(iii).getId().equals(materialId)) {
                                    String optionValue = size.get(i).getOptionValue();
                                    if (StringUtils.isNotBlank(optionValue)) {
                                        String[] split = optionValue.split(",");
                                        if (split.length == 2) {
                                            int length = Integer.parseInt(split[0]);
                                            int wide = Integer.parseInt(split[1]);
                                            if (paperLength.intValue() >= length && paperWide.intValue() >= wide) {
                                                //比较克重是否在机器范围内
                                                String optionName2 = materiaEntity.get(iii).getOptionName2();
                                                if (StringUtils.isBlank(optionName2)) {
                                                    return "检测到克重数据内容为空,请联系管理员查找数据来源是否被删除!";
                                                }
                                                try {
                                                    Integer keZhong = Integer.parseInt(optionName2);
                                                    if (minWeight.intValue() <= keZhong.intValue() && keZhong.intValue() <= maxWeight) {
                                                        //比较机器的宽
                                                        if (minLength <= paperLength.intValue() && paperLength.intValue() <= maxLength) {
                                                            //比较机器的宽
                                                            if (minWide <= paperWide.intValue() && paperWide.intValue() <= maxWide) {
                                                                flagB = false;
                                                                break lableB;
                                                            }
                                                        }
                                                    }
                                                } catch (RRException e) {
                                                    String message = "检测到克重选项id:" + materiaEntity.get(iii).getId() + "数字化解析值" + optionName2 + "异常!";
                                                    throw new RRException(message);

                                                    //return "检测到克重选项id:"+ materiaEntity.get(iii).getId() +"数字化解析值"+ optionName2 +"异常!";
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if (flagB) {
//							QuoteAttributeOptionEntity quoteAttributeOptionEntity = quoteAttributeOptionService.selectById(selectedMaterialIds.get(iii));
                            return "尺寸长宽:" + size.get(i).getOptionValue() + ",颜色:" + colour.get(ii).getOptionName() + ",材料类型:" + materiaEntity.get(iii).getOptionName() + ",克重:" + materiaEntity.get(iii).getOptionName2() + "找不到组合价";
                        }
                    }
                }
            }
        } else if (fastPriceVoList != null && fastPriceVoList.size() > 1) {
            //多部件
            List<QuoteAttributeOptionEntity> quoteAttributeOptionEntityList = null;
            List<List<QuoteAttributeOptionEntity>> colorAttriOptionEntityList = null;
            for (int i = 0; i < fastPriceVoList.size(); i++) {
                if (fastPriceVoList.get(i).getSelectedMaterialIds() == null) {
                    //是主部件-->查询这里面的尺寸
//					fastPriceVoList.get(i).getSelectedAttributeIds()
                    quoteAttributeOptionEntityList = this.baseMapper.getQuoteAttributeOptionByAttributeTypeValueFromOptionIds(StringUtils.join(fastPriceVoList.get(i).getSelectedAttributeIds(), ","), "size");
                    break;
                }
            }
            if (quoteAttributeOptionEntityList != null && quoteAttributeOptionEntityList.size() > 0) {
                for (int j = 0; j < fastPriceVoList.size(); j++) {
                    if (fastPriceVoList.get(j).getSelectedMaterialIds() != null) {
                        //不是主部件,必须有颜色和材料选项
                        //获得选项里面的颜色选项
                        List<QuoteAttributeOptionEntity> colourOptionEntityList = this.baseMapper.getQuoteAttributeOptionByAttributeTypeValueFromOptionIds(StringUtils.join(fastPriceVoList.get(j).getSelectedAttributeIds(), ","), "colour");
//						colorAttriOptionEntityList.add(colourOptionEntityList);
                        List<Integer> selectedMaterialIds = fastPriceVoList.get(j).getSelectedMaterialIds();
                        if (!(selectedMaterialIds != null && selectedMaterialIds.size() > 0)) {
                            return "不允许材料为空";
                        }
                        //先校验这些材料是否存在切不为0
//						String s = verifyMaterialPrice(selectedMaterialIds,factoryId);
//						if(!s.equals("ok")){
//							return s;
//						}
                        //遍历成品尺寸
                        for (int k = 0; k < quoteAttributeOptionEntityList.size(); k++) {
                            //遍历颜色
                            for (int kk = 0; kk < colourOptionEntityList.size(); kk++) {
                                //遍历材料选项-->克重
                                List<QuoteAttributeOptionEntity> materiaEntity = this.baseMapper.getQuoteAttributeOptionByAttributeTypeValueFromOptionIds(StringUtils.join(selectedMaterialIds, ","), "material");
                                //遍历结果集,找匹配
                                for (int kkk = 0; kkk < materiaEntity.size(); kkk++) {
                                    //遍历所有的数据,查询比较
                                    Boolean flag = true;
                                    lableA:
                                    for (int w = 0; w < verifyFastPriceDtoList.size(); w++) {
                                        //获得颜色id
                                        Integer colourId = verifyFastPriceDtoList.get(w).getColourId();
                                        //获得材料克重id
                                        Integer materialId = verifyFastPriceDtoList.get(w).getMaterialId();
                                        //获得材料长
                                        Integer paperLength = verifyFastPriceDtoList.get(w).getPaperLength();
                                        //获得材料宽
                                        Integer paperWide = verifyFastPriceDtoList.get(w).getPaperWide();
                                        //获得机器最小克重
                                        Integer minWeight = verifyFastPriceDtoList.get(w).getMinWeight();
                                        //获得机器最大克重
                                        Integer maxWeight = verifyFastPriceDtoList.get(w).getMaxWeight();
                                        //获得机器最小长
                                        Integer minLength = verifyFastPriceDtoList.get(w).getMinLength();
                                        //获得机器最小宽
                                        Integer minWide = verifyFastPriceDtoList.get(w).getMinWide();
                                        //获得机器最大长
                                        Integer maxLength = verifyFastPriceDtoList.get(w).getMaxLength();
                                        //获得机器最大宽
                                        Integer maxWide = verifyFastPriceDtoList.get(w).getMaxWide();
                                        //先比较颜色和材料是否符合
                                        if (colourOptionEntityList.get(kk).getId().equals(colourId) && materiaEntity.get(kkk).getId().equals(materialId)) {
                                            String optionValue = quoteAttributeOptionEntityList.get(k).getOptionValue();
                                            if (StringUtils.isNotBlank(optionValue)) {
                                                String[] split = optionValue.split(",");
                                                if (split.length == 2) {
                                                    int length = Integer.parseInt(split[0]);
                                                    int wide = Integer.parseInt(split[1]);
                                                    if (paperLength.intValue() >= length && paperWide.intValue() >= wide) {
//														//找到满足条件的了
//														flag = false;
//														break lableA;
                                                        //比较克重是否在机器范围内
                                                        String optionName2 = materiaEntity.get(kkk).getOptionName2();
                                                        if (StringUtils.isBlank(optionName2)) {
                                                            return "检测到克重数据内容为空,请联系管理员查找数据来源是否被删除!";
                                                        }
                                                        try {
                                                            Integer keZhong = Integer.parseInt(optionName2);
                                                            if (minWeight.intValue() <= keZhong.intValue() && keZhong.intValue() <= maxWeight.intValue()) {
                                                                //比较机器的宽
                                                                if (minLength <= paperLength.intValue() && paperLength.intValue() <= maxLength) {
                                                                    //比较机器的宽
                                                                    if (minWide <= paperWide.intValue() && paperWide.intValue() <= maxWide) {
                                                                        flag = false;
                                                                        break lableA;
                                                                    }
                                                                }
                                                            }
                                                        } catch (Exception e) {
                                                            String message = "检测到克重选项id:" + materiaEntity.get(kkk).getId() + "数字化解析值" + optionName2 + "异常!";
                                                            throw new RRException(message);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    if (flag) {
//										QuoteAttributeOptionEntity quoteAttributeOptionEntity = quoteAttributeOptionService.selectById(selectedMaterialIds.get(kkk));
                                        return "尺寸:" + quoteAttributeOptionEntityList.get(k).getOptionValue() + ",颜色:" + colourOptionEntityList.get(kk).getOptionName()
                                                + ",材料类型:" + materiaEntity.get(kkk).getOptionName() + ",克重:" + materiaEntity.get(kkk).getOptionName2() + "找不到组合价";
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                return "没有成品尺寸,无法找到匹配价格";
            }
        }
        //获得所有的工艺,校验价格是否存在
        //当所有组合计价完成,还要找到所有的工艺,判断价格
        if (fastPriceVoList != null && fastPriceVoList.size() > 0) {
            for (int i = 0; i < fastPriceVoList.size(); i++) {
                List<Integer> list = this.baseMapper.quotePriceCount(StringUtils.join(fastPriceVoList.get(i).getAllSelectedOptionIds(), ","));
                List<Integer> list1 = this.baseMapper.quotePrice(StringUtils.join(fastPriceVoList.get(i).getAllSelectedOptionIds(), ","), factoryId);
                if (list.size() <= list1.size()) {
                    continue;
                } else {
                    List<Integer> noPriceCraftIds = New.arrayList();
                    for (Integer optionId : list) {
                        if (list1.indexOf(optionId) == -1) {
                            noPriceCraftIds.add(optionId);
                        }
                    }
                    StringBuffer stringBuffer = new StringBuffer();
                    if (noPriceCraftIds != null && noPriceCraftIds.size() > 0) {
                        List<QuoteAttributeOptionEntity> quoteAttributeOptionEntityList = quoteAttributeOptionService.selectBatchIds(noPriceCraftIds);
                        if (quoteAttributeOptionEntityList != null && quoteAttributeOptionEntityList.size() > 0) {
                            for (QuoteAttributeOptionEntity quoteAttributeOptionEntity : quoteAttributeOptionEntityList) {
                                stringBuffer.append("工艺选项名:");
                                stringBuffer.append(quoteAttributeOptionEntity.getOptionName());
                                stringBuffer.append("工艺选项id");
                                stringBuffer.append(quoteAttributeOptionEntity.getId());
                                stringBuffer.append("没有找到工艺价格;  ");
                            }
                        }
                    }
                    return stringBuffer.toString();
                }
            }
        }
        return "ok";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void hideGoods(Long goodsId, Long userId) {
        //开始商品编辑记录
        Map<String, String> monitor = New.hashMap();
        GoodsMonitorEntity goodsMonitorEntity = new GoodsMonitorEntity();
        goodsMonitorEntity.setCreateId(userId);
        goodsMonitorEntity.setMessage("屏蔽下列商品:" + goodsId);
        goodsMonitorEntity.setSdbId(goodsId.toString());
        goodsMonitorEntity.setType("Goods");
        goodsMonitorService.insert(goodsMonitorEntity);
        this.baseMapper.hideGoods(goodsId);
    }

    @Override
    public void opMarkGoodsByGoodsId(Integer goodsId, Boolean mark) {
        this.baseMapper.opMarkGoodsByGoodsId(goodsId, mark);
    }

    @Override
    public void examineGoods(Integer goodsId, Integer examine) {
        this.baseMapper.examineGoods(goodsId, examine);
    }

    @Override
    /**
     * 商户冻结冻结商品
     */
    @Transactional(rollbackFor = Exception.class)
    public void frozenGoods(Long sellerId, String frozenName) {
        Map<String, Object> map = New.hashMap();
        map.put("seller_id", sellerId);
        List<GoodsEntity> goodsEntityList = this.baseMapper.selectByMap(map);
        List<FrozenGoodsEntity> frozenGoodsEntityList = null;
        if (goodsEntityList != null && goodsEntityList.size() > 0) {
            frozenGoodsEntityList = New.arrayList();
            for (int i = 0; i < goodsEntityList.size(); i++) {
                FrozenGoodsEntity frozenGoodsEntity = new FrozenGoodsEntity();
                frozenGoodsEntity.setGoodsId(goodsEntityList.get(i).getGoodsId());
                frozenGoodsEntity.setMarketable(goodsEntityList.get(i).getMarketable());
                frozenGoodsEntity.setFrozenFlag(false);
                frozenGoodsEntity.setFrozenUser(frozenName);
                frozenGoodsEntity.setSellerId(goodsEntityList.get(i).getSellerId());
                frozenGoodsEntityList.add(frozenGoodsEntity);
            }
        }
        if (frozenGoodsEntityList != null && frozenGoodsEntityList.size() > 0) {
            frozenGoodsService.insertBatch(frozenGoodsEntityList);
        }
        this.baseMapper.flagDelBySellerId(sellerId);
    }


    @Override
    /**
     * 商户解冻,商品解冻
     */
    @Transactional(rollbackFor = Exception.class)
    public void unfreezeGoods(Long sellerId, String unfreezeName) {
        Map<String, Object> map = New.hashMap();
        map.put("seller_id", sellerId);
        map.put("frozen_flag", 0);
        List<FrozenGoodsEntity> frozenGoodsEntities = frozenGoodsService.selectByMap(map);
        if (frozenGoodsEntities != null && frozenGoodsEntities.size() > 0) {
            for (int i = 0; i < frozenGoodsEntities.size(); i++) {
                GoodsEntity goodsEntity = new GoodsEntity();
                goodsEntity.setGoodsId(frozenGoodsEntities.get(i).getGoodsId());
                goodsEntity.setMarketable(frozenGoodsEntities.get(i).getMarketable());
                this.baseMapper.updateById(goodsEntity);
            }
        }
        frozenGoodsService.unfreezeBySellerId(sellerId, unfreezeName);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editQuoteGood(QuoteVO quoteVO) {

//		GoodsMonitorEntity goodsMonitorEntity = GoodsMonitorUtils.packingData(oldGoodsOption, quoteVO, UserUtils.getCurentUser().getUserId());
//		if(goodsMonitorEntity.getSdbId() != null){
//			goodsMonitorService.insert(goodsMonitorEntity);
//		}
        //首先更新goods部分的内容信息
        GoodsEntity goods = quoteVO.getGoodsEntity();

        //记录报价商品--------------------
        GoodsEntity oldGoodsEntity = this.baseMapper.selectById(goods.getGoodsId());
        GoodsMonitorEntity goodsMonitorEntity = GoodsMonitorUtils.packingData(oldGoodsEntity, goods, Long.valueOf(goods.getSellerId()));
        if (goodsMonitorEntity.getSdbId() != null) {
            goodsMonitorService.insert(goodsMonitorEntity);
        }
        // 按集合删除图片
        List<String> delImageIds = goods.getDelImageIds();
        String delImages = org.apache.commons.lang3.StringUtils.join(delImageIds, ",");
        List<Integer> list = changeStr2List(delImages);
        if (list != null && list.size() > 0) {
            goodsImageDao.fagDelImageByIds(list);
        }
        // 更新商品
        goodsDao.updateById(goods);
        // 给默认图片添加goodsId
        if (imageVerify(goods.getImageUrls())) {
//            goodsImageDao.updateImageByGoodsId(goods.getGoodsId(), goods.getImageUrls());
            goodsImageService.newImageUpdate(goods.getGoodsId(),changeStr2List(goods.getImageUrls()));
        }
        // 给详细图片添加goodsId
        if (imageVerify(goods.getInfoUrls())) {
//            goodsImageDao.updateImageByGoodsId(goods.getGoodsId(), goods.getInfoUrls());
            goodsImageService.newImageUpdate(goods.getGoodsId(),changeStr2List(goods.getInfoUrls()));
        }
        // 给视频添加goodsId
        if (imageVerify(goods.getVideoUrl())) {
//            goodsImageDao.updateImageByGoodsId(goods.getGoodsId(), goods.getVideoUrl());
            goodsImageService.newImageUpdate(goods.getGoodsId(),changeStr2List(goods.getVideoUrl()));
        }

        //然后更新productBaseInfo
//		productBaseInfoService.delFlagQuoteProductByGoodsId(goods.getGoodsId());
        //productBaseInfo从标记删除变为物理删除
        productBaseInfoService.deleteProductBaseInfoByGoodsId(goods.getGoodsId());
        List<QuoteProductBaseInfoVO> quoteProductBaseInfoVOList = quoteVO.getQuoteProductBaseInfoVOList();
        ArrayList<ProductBaseInfoEntity> productBaseInfoEntities = handlerProductBaseInfoEntities(goods, quoteProductBaseInfoVOList);
        productBaseInfoService.insertBatch(productBaseInfoEntities);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pushQuoteGood(QuoteVO quoteVO) {
        GoodsEntity goodsEntity = quoteVO.getGoodsEntity();
        goodsEntity.setGoodsNo(builderGoodsBn(goodsEntity.getCategoryId()));
        goodsDao.insert(goodsEntity);
        List<String> delImageIds = goodsEntity.getDelImageIds();
        String delImages = org.apache.commons.lang3.StringUtils.join(delImageIds, ",");
        List<Integer> list = changeStr2List(delImages);
        if (list != null && list.size() > 0) {
            goodsImageDao.fagDelImageByIds(list);
        }
//        if (delImageIds != null && delImageIds.size() > 0) {
//            goodsImageDao.fagDelImageByIds(StringUtils.join(delImageIds, ","));
//        }
        // 给默认图片添加goodsId
        if (imageVerify(goodsEntity.getImageUrls())) {
//            goodsImageDao.updateImageByGoodsId(goodsEntity.getGoodsId(), goodsEntity.getImageUrls());
            goodsImageService.newImageUpdate(goodsEntity.getGoodsId(),changeStr2List(goodsEntity.getImageUrls()));
        }
        // 给详细图片添加goodsId
        if (imageVerify(goodsEntity.getInfoUrls())) {
//            goodsImageDao.updateImageByGoodsId(goodsEntity.getGoodsId(), goodsEntity.getInfoUrls());
            goodsImageService.newImageUpdate(goodsEntity.getGoodsId(),changeStr2List(goodsEntity.getInfoUrls()));
        }
        // 给视频添加goodsId
        if (imageVerify(goodsEntity.getVideoUrl())) {
//            goodsImageDao.updateImageByGoodsId(goodsEntity.getGoodsId(), goodsEntity.getVideoUrl());
            goodsImageService.newImageUpdate(goodsEntity.getGoodsId(),changeStr2List(goodsEntity.getVideoUrl()));
        }
//		goodsDao.pushGoods(goodsEntity);
        List<QuoteProductBaseInfoVO> quoteProductBaseInfoVOList = quoteVO.getQuoteProductBaseInfoVOList();
//        ArrayList<QuoteProductBaseInfoRelationEntity> QuoteProductBaseInfoRelationList = new ArrayList<>();
        ArrayList<ProductBaseInfoEntity> productBaseInfoEntityList = handlerProductBaseInfoEntities(goodsEntity, quoteProductBaseInfoVOList);
        productBaseInfoService.insertBatch(productBaseInfoEntityList);
//        quoteProductBaseInfoRelationService.insertBatch(ProductBaseInfoEntityList);
        //通知mq goodsId
//		loadGoodsCacheEvent(goodsEntity.getGoodsId());
    }

    /**
     * 封装对象
     *
     * @param goodsEntity
     * @param quoteProductBaseInfoVOList
     * @return
     */
    private ArrayList<ProductBaseInfoEntity> handlerProductBaseInfoEntities(GoodsEntity goodsEntity, List<QuoteProductBaseInfoVO> quoteProductBaseInfoVOList) {
        ArrayList<ProductBaseInfoEntity> ProductBaseInfoEntityList = new ArrayList<>();
        for (int i = 0; i < quoteProductBaseInfoVOList.size(); i++) {
            List<QuoteProductBaseInfoEntity> quoteProductBaseInfoEntities = quoteProductBaseInfoService.handleWebDataToBaseInfoList(quoteProductBaseInfoVOList.get(i));
            for (int j = 0; j < quoteProductBaseInfoEntities.size(); j++) {
//                QuoteProductBaseInfoRelationEntity quoteProductBaseInfoRelationEntity = new QuoteProductBaseInfoRelationEntity();
                ProductBaseInfoEntity productBaseInfoEntity = new ProductBaseInfoEntity();
                productBaseInfoEntity.setGoodsId(goodsEntity.getGoodsId());
                productBaseInfoEntity.setPartsId(quoteProductBaseInfoEntities.get(j).getPartsId());
                productBaseInfoEntity.setCategoryId(goodsEntity.getCategoryId());
                productBaseInfoEntity.setAttributeId(quoteProductBaseInfoEntities.get(j).getAttributeId());
                productBaseInfoEntity.setOptionId(quoteProductBaseInfoEntities.get(j).getOptionId());
                productBaseInfoEntity.setWhetherDefault(quoteProductBaseInfoEntities.get(j).getIsDefault());
                productBaseInfoEntity.setCreateUser(quoteProductBaseInfoEntities.get(j).getCreateUser());
                productBaseInfoEntity.setUpdateUser(quoteProductBaseInfoEntities.get(j).getCreateUser());
                ProductBaseInfoEntityList.add(productBaseInfoEntity);
            }
        }
        return ProductBaseInfoEntityList;
    }

    /**
     * 根据spu,返回规格属性选项数据模型
     *
     * @param goodsProperty
     */
    @Override
    public Map<String, Object> getAttributeAndCraftData(GoodsEntity goodsProperty) {
        Map<String, Object> result = new HashMap<>();
        List<Object> attributeList = new ArrayList<>();
        List<Object> craftAttributeList = new ArrayList<>();
        //旧方法一:按照商品绑定的分类找到模板下面的规格,遍历找到规格下的所有选项
		/*List<GoodsAttributeEntity> attributes = goodsAttributeService.selectAttribute(goodsProperty.getGoodsId());
		for (int i = 0;i<attributes.size();i++){
			HashMap<String, Object> map = new HashMap<>();
			map.put("disabled",0);
			map.put("attribute_id",attributes.get(i).getAttributeId());
			List<GoodsOptionEntity> goodsOptionEntities = goodsOptionDao.selectByMap(map);

			attributes.get(i).setGoodsOptionList(goodsOptionEntities);
			//设置选中的optionId
			List<GoodsOptionEntity> selectedList = goodsOptionDao.getSelectedOptions(goodsProperty.getGoodsId(),attributes.get(i).getAttributeId());
			attributes.get(i).setOptionSelectedList(selectedList);
			if(attributes.get(i).getAttributeType().equals("craft")){
				attributes.get(i).setJoinAttribute(true);
				craftAttributeList.add(attributes.get(i));
			}else{
				attributeList.add(attributes.get(i));
			}
		}
		List<GoodsAttributeEntity> craft = goodsAttributeService.selectCraft(goodsProperty.getGoodsId());
		if(craft.size()!=0){
			for(int i = 0;i<craft.size();i++){
				HashMap<String, Object> map = new HashMap<>();
				map.put("disabled",0);
				map.put("attribute_id",craft.get(i).getAttributeId());
				//所有的选项
				List<GoodsOptionEntity> goodsOptionEntities = goodsOptionDao.selectByMap(map);
				craft.get(i).setGoodsOptionList(goodsOptionEntities);
				List<GoodsOptionEntity> selectedCraftList = goodsOptionDao.getSelectedCraftOptions(goodsProperty.getGoodsId(),craft.get(i).getAttributeId());
				craft.get(i).setOptionSelectedList(selectedCraftList);
				craftAttributeList.add(craft.get(i));
			}
		}*/
        //新方法二:按照商品绑定的分类找到模板下的optionJson,
        GoodsCategoryEntity categoryEntity = goodsCategoryService.selectById(goodsProperty.getCategoryId());
        GoodsTemplateEntity template = goodsTemplateService.getTemplateByCatId(categoryEntity.getCategoryId());
        String optionJson = template.getOptionJson();
        net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(optionJson);
        //在这里拿到原本属于工艺的规格集-->作为joinAttributeCraft使用
        //下面的方法有问题,不过参与sku生成工艺功已取消,所有不做修改了
        Long craftAttributeId = goodsAttributeService.getCraftAttributeByGoodsId(goodsProperty.getGoodsId());
        for (int i = 0; i < jsonArray.size(); i++) {
            net.sf.json.JSONObject jsonObject = jsonArray.getJSONObject(i);
            Long attributeId = Long.valueOf(jsonObject.get("attributeId").toString());
            net.sf.json.JSONArray optionId = jsonObject.getJSONArray("optionId");
            //根据attributeId获得规格对象
            GoodsAttributeEntity goodsAttributeEntity = goodsAttributeService.selectById(attributeId);
            //根据规格对象获得规格下所有的选项
//			List<GoodsOptionEntity> goodsOptionEntityList = goodsOptionDao.loadTempOptionsByAttributeId(attributeId);
            List<GoodsOptionEntity> goodsOptionEntityList = goodsOptionDao.selectByOptionIds(optionId.join(","));
            //获得私有选项
            List<GoodsOptionEntity> privateGoodsOptionEntityList = goodsOptionDao.selectPrivateOption(attributeId, goodsProperty.getSellerId());
            if (privateGoodsOptionEntityList != null && privateGoodsOptionEntityList.size() > 0) {
//				goodsOptionEntityList.add(goodsOptionEntity);
                goodsOptionEntityList.addAll(privateGoodsOptionEntityList);
            }
            goodsAttributeEntity.setGoodsOptionList(goodsOptionEntityList);
            if ("normal".equals(goodsAttributeEntity.getAttributeType())) {
                attributeList.add(goodsAttributeEntity);
                //根据商品信息获得用户已经选择的规格选项集
                List<GoodsOptionEntity> selectedList = goodsOptionDao.getSelectedOptions(goodsProperty.getGoodsId(), goodsAttributeEntity.getAttributeId());
                goodsAttributeEntity.setOptionSelectedList(selectedList);
            } else if ("craft".equals(goodsAttributeEntity.getAttributeType())) {
                if (attributeId.equals(craftAttributeId)) {
                    goodsAttributeEntity.setJoinAttribute(true);
                } else {
                    goodsAttributeEntity.setJoinAttribute(false);
                }
                //根据商品信息获得用户已经选择的规格选项集
                List<GoodsOptionEntity> selectedList = goodsOptionDao.getSelectedCraftOptions(goodsProperty.getGoodsId(), goodsAttributeEntity.getAttributeId());
                goodsAttributeEntity.setOptionSelectedList(selectedList);
                craftAttributeList.add(goodsAttributeEntity);
            }
        }
        result.put("attributeList", attributeList);
        result.put("craftAttributeList", craftAttributeList);

        return result;
    }

    /**
     * 根据商品id,获得所有选中的option
     *
     * @param goodsId
     * @return
     */
    @Override
    public List<GoodsOptionEntity> getOptionsByGoodsId(Long goodsId) {
        return this.baseMapper.getOptionsByGoodsId(goodsId);
    }

    /**
     * 发布连锁店标品
     *
     * @param goods
     * @param sellerInfoEntities
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pushChainGoods(GoodsEntity goods, List<SellerInfoEntity> sellerInfoEntities) {
        for (int i = 0; i < sellerInfoEntities.size(); i++) {
            goods.setSellerId(sellerInfoEntities.get(i).getSellerId());
            this.pushGood(goods);
        }
    }

    /**
     * 连锁店发布报价商品
     *
     * @param quoteVO1
     * @param sellerInfoEntities
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pushChainQuoteGood(QuoteVO quoteVO1, List<SellerInfoEntity> sellerInfoEntities) {
        for (int i = 0; i < sellerInfoEntities.size(); i++) {
            quoteVO1.getGoodsEntity().setSellerId(sellerInfoEntities.get(i).getSellerId());
            this.pushQuoteGood(quoteVO1);
        }
    }


    /**
     * 设置规格属性id集
     *
     * @param goods
     * @param itemList
     * @param i
     * @return
     */
    private String setOptionIds(GoodsEntity goods, JSONArray itemList, int i) {
        JSONObject spec = itemList.getJSONObject(i).getJSONObject("spec");
        String[] split = goods.getAttributeNames().split(",");
        // 存放规格option_id
        ArrayList<Integer> list = new ArrayList<>();
        for (String str : split) {
            JSONObject jsonObject1 = spec.getJSONObject(str);
            Integer optionId;
            try{
                optionId = Integer.parseInt(jsonObject1.getString("optionId"));
            }catch (Exception e){
                throw new RRException("商品发布optionId解析异常");
            }
            list.add(optionId);
        }
        Collections.sort(list);
        // 设置规格属性id集
        return StringUtils.join(list, ",");
    }

    /**
     * 设置sku相关属性store/weight/totalPrice/marketPrice
     *
     * @param itemList
     * @param i
     * @param goodsProduct
     * @return
     */
    private Map<String, BigDecimal> setSkuNum(JSONArray itemList, int i, GoodsProductEntity goodsProduct, GoodsEntity goods) {
        Map<String, BigDecimal> map = New.hashMap();
        // 设置库存
        String store = itemList.getJSONObject(i).getString("store");
        if (StringUtils.isNotBlank(store)) {
            BigDecimal productStore = new BigDecimal(store).setScale(2, BigDecimal.ROUND_DOWN);// 小数位 直接舍去
            goodsProduct.setStore(productStore);
        }
        // 设置重量
        String weight = itemList.getJSONObject(i).getString("weight");
        BigDecimal productWeight = new BigDecimal(weight).setScale(3, BigDecimal.ROUND_DOWN);// 小数位 直接舍去
        goodsProduct.setWeight(productWeight);
        // 设置成本价
        String costPrice = itemList.getJSONObject(i).getString("cost");
        BigDecimal productCostPrice = new BigDecimal(costPrice).setScale(2, BigDecimal.ROUND_DOWN);// 小数位 直接舍去
        goodsProduct.setCost(productCostPrice);
//		 设置总价价格
//		String totalPrice = itemList.getJSONObject(i).getString("totalPrice");
//		BigDecimal productTotalPrice = new BigDecimal(totalPrice).setScale(2, BigDecimal.ROUND_DOWN);// 小数位 直接舍去
//		下列一行代码需要注释
//		goodsProduct.setTotalPrice(productTotalPrice);
        // 设置平板成本价
        String lCostPrice = itemList.getJSONObject(i).getString("lCost");
        BigDecimal productLCostPrice = null;
        if (StringUtil.isNotEmpty(lCostPrice)) {
            productLCostPrice = new BigDecimal(lCostPrice).setScale(2, BigDecimal.ROUND_DOWN);// 小数位 直接舍去
            goodsProduct.setlCost(productLCostPrice);
        }
        BigDecimal productTotalPrice = null;
        BigDecimal productTotalPricePop = null;
//		如果需要优化,可以在这里做相应的校验判断---------------------------------
        if (goods.getStageType() == 0) {
//			设置两个价格-->两个平台的售价
			/*//获得紫云网价格
			BigDecimal ziyunPriceCoefficient = goods.getZiyunPriceCoefficient();
			productTotalPrice = productCostPrice.multiply(ziyunPriceCoefficient).setScale(2, BigDecimal.ROUND_UP);
			goodsProduct.setTotalPrice(productTotalPrice);
			BigDecimal popPriceCoefficient = goods.getPopPriceCoefficient();
			//获得pop平台价格
			productTotalPricePop = productCostPrice.multiply(popPriceCoefficient).setScale(2, BigDecimal.ROUND_UP);
			goodsProduct.setTotalPricePop(productTotalPricePop);
			map.put("productTotalPrice",productTotalPrice);
			map.put("productTotalPricePop",productTotalPricePop);*/
            //设置总价价格
            String totalPrice = itemList.getJSONObject(i).getString("totalPrice");
            productTotalPrice = new BigDecimal(totalPrice).setScale(2, BigDecimal.ROUND_DOWN);// 小数位 直接舍去
            goodsProduct.setTotalPrice(productTotalPrice);
            map.put("productTotalPrice", productTotalPrice);
            //设置总价价格
            String totalPricePop = itemList.getJSONObject(i).getString("totalPricePop");
            productTotalPricePop = new BigDecimal(totalPricePop).setScale(2, BigDecimal.ROUND_DOWN);// 小数位 直接舍去
            goodsProduct.setTotalPricePop(productTotalPricePop);
            map.put("productTotalPricePop", productTotalPricePop);
			/*if (productLCostPrice != null) {
				BigDecimal ziyunLPriceCoefficient = productLCostPrice.multiply(ziyunPriceCoefficient).setScale(2, BigDecimal.ROUND_UP);
				goodsProduct.setExpandPrice(ziyunLPriceCoefficient);
				BigDecimal popLPriceCoefficient = productLCostPrice.multiply(popPriceCoefficient).setScale(2, BigDecimal.ROUND_UP);
				goodsProduct.setExpandPricePop(popLPriceCoefficient);
			}*/
            //若紫云平板成本价不为空,则该商品含平板成本价
            String expandPrice = itemList.getJSONObject(i).getString("expandPrice");
            if (StringUtil.isNotEmpty(expandPrice)) {
                BigDecimal productExpandPrice = new BigDecimal(expandPrice).setScale(2, BigDecimal.ROUND_UP);
                goodsProduct.setExpandPrice(productExpandPrice);
            }
            //若pop平板成本价不为空,则该商品含平板成本价
            String expandPricePop = itemList.getJSONObject(i).getString("expandPricePop");
            if (StringUtil.isNotEmpty(expandPricePop)) {
                BigDecimal productExpandPricePop = new BigDecimal(expandPricePop).setScale(2, BigDecimal.ROUND_UP);
                goodsProduct.setExpandPricePop(productExpandPricePop);
            }
        } else if (goods.getStageType() == 1) {
//			设置紫云网价格
			/*BigDecimal ziyunPriceCoefficient = goods.getZiyunPriceCoefficient();
			productTotalPrice = productCostPrice.multiply(ziyunPriceCoefficient).setScale(2, BigDecimal.ROUND_UP);
			goodsProduct.setTotalPrice(productTotalPrice);
			map.put("productTotalPrice",productTotalPrice);*/
            //设置总价价格
            String totalPrice = itemList.getJSONObject(i).getString("totalPrice");
            productTotalPrice = new BigDecimal(totalPrice).setScale(2, BigDecimal.ROUND_DOWN);// 小数位 直接舍去
            goodsProduct.setTotalPrice(productTotalPrice);
            map.put("productTotalPrice", productTotalPrice);
            //特别设置平板价
            // 设置平板总价
            //若平板成本价不为空,则该商品含平板成本价
            String expandPrice = itemList.getJSONObject(i).getString("expandPrice");
            if (StringUtil.isNotEmpty(expandPrice)) {
                BigDecimal productExpandPrice = new BigDecimal(expandPrice).setScale(2, BigDecimal.ROUND_UP);
                goodsProduct.setExpandPrice(productExpandPrice);
            }
        } else if (goods.getStageType() == 2) {
            //设置pop平台价格
			/*BigDecimal popPriceCoefficient = goods.getPopPriceCoefficient();
			productTotalPricePop = productCostPrice.multiply(popPriceCoefficient).setScale(2, BigDecimal.ROUND_UP);
			goodsProduct.setTotalPricePop(productTotalPricePop);
			map.put("productTotalPricePop",productTotalPricePop);*/
            //设置总价价格
            String totalPricePop = itemList.getJSONObject(i).getString("totalPricePop");
            productTotalPricePop = new BigDecimal(totalPricePop).setScale(2, BigDecimal.ROUND_DOWN);// 小数位 直接舍去
            goodsProduct.setTotalPricePop(productTotalPricePop);
            map.put("productTotalPricePop", productTotalPricePop);
            //若平板成本价不为空,则该商品含平板成本价
            String expandPricePop = itemList.getJSONObject(i).getString("expandPricePop");
            if (StringUtil.isNotEmpty(expandPricePop)) {
                BigDecimal productExpandPricePop = new BigDecimal(expandPricePop).setScale(2, BigDecimal.ROUND_UP);
                goodsProduct.setExpandPricePop(productExpandPricePop);
            }
//			这是一个备用方案,当发布pop平台的时候,将productTotalPriceExpend设置给productTotalPrice;
        }

//		 设置市场价
        String marketPrice = itemList.getJSONObject(i).getString("marketPrice");
        if (StringUtil.isNotEmpty(marketPrice)) {
            BigDecimal productMarketPrice = new BigDecimal(marketPrice).setScale(2, BigDecimal.ROUND_DOWN);// 小数位 直接舍去
            goodsProduct.setMarketPrice(productMarketPrice);
        }
        // 设置平板市场价
        String lMarketPrice = itemList.getJSONObject(i).getString("lMarketPrice");
        if (StringUtil.isNotEmpty(lMarketPrice)) {
            BigDecimal productLMarketPrice = new BigDecimal(lMarketPrice).setScale(2, BigDecimal.ROUND_DOWN);// 小数位 直接舍去
            goodsProduct.setlMarketPrice(productLMarketPrice);
        }
        //如果是复印纸,设置令价
        if ("copy".equals(goods.getGoodsType())) {
            calculateCopyPrice(goodsProduct, goods, productTotalPrice, productTotalPricePop);

//			BigDecimal lprice = priceTransformLprice(copyWeight, pack, sacle, productTotalPrice);
//            goodsProduct.setExpandPrice(lprice);
        }
        // 设置单位,上下架状态,最小起订量
        String unit = itemList.getJSONObject(i).getString("unit");
        goodsProduct.setUnit(unit);
        String marketable = itemList.getJSONObject(i).getString("marketable");
        goodsProduct.setMarketable(marketable);
        String minBuyNum = itemList.getJSONObject(i).getString("minBuyNum");
        if (StringUtil.isNotEmpty(minBuyNum)) {
            BigDecimal productMinBuyNum = new BigDecimal(minBuyNum).setScale(2, BigDecimal.ROUND_DOWN);// 小数位 直接舍去
            goodsProduct.setMinBuyNum(productMinBuyNum);
        }
        return map;
    }

    private void calculateCopyPrice(GoodsProductEntity goodsProduct, GoodsEntity goods, BigDecimal productTotalPrice, BigDecimal productTotalPricePop) {
        //计算令价-->根据optionIds拿到attribute_value_key,匹配包数,纸张规格,克重
        List<Map<String, String>> attributeAndOptionList = goodsAttributeService.selectListByOptionIds(goodsProduct.getOptionIds());
        //定义包数,纸张规格,克重
        Integer copyWeight = 0;
        Integer pack = 0;
        String sacle = "";
        for (Map<String, String> attributeAndOption : attributeAndOptionList) {
            if ("weight".equals(attributeAndOption.get("attribute_value_key"))) {
                copyWeight = Integer.parseInt(attributeAndOption.get("option_value"));
            }
            if ("packets".equals(attributeAndOption.get("attribute_value_key"))) {
                pack = Integer.parseInt(attributeAndOption.get("option_value"));
            }
            if ("sheetSize".equals(attributeAndOption.get("attribute_value_key"))) {
                sacle = attributeAndOption.get("option_value");
            }
        }
        BigDecimal lprice = null;//紫云网复印纸令价
        BigDecimal lpriceExpend = null;//pop平台复印纸令价
        if (goods.getStageType() == 0) {
            //设置两个价格
            lprice = priceTransformLprice(copyWeight, pack, sacle, productTotalPrice);
            lpriceExpend = priceTransformLprice(copyWeight, pack, sacle, productTotalPricePop);
            goodsProduct.setExpandPrice(lprice);
            goodsProduct.setExpandPricePop(lpriceExpend);
        } else if (goods.getStageType() == 1) {
            //设置紫云网价格
            lprice = priceTransformLprice(copyWeight, pack, sacle, productTotalPrice);
            goodsProduct.setExpandPrice(lprice);
        } else if (goods.getStageType() == 2) {
            //设置pop平台价格
            lpriceExpend = priceTransformLprice(copyWeight, pack, sacle, productTotalPricePop);
            goodsProduct.setExpandPricePop(lpriceExpend);
        }
    }

    /**
     * 设置默认sku
     *
     * @param singlePriceList
     * @param productList
     */
    //defaultOptionIds  defaultCraftOptionIds
    private Map<String, String> setDefaultSku(List<BigDecimal> singlePriceList, List<GoodsProductEntity> productList, String defaultOptionIds, String defaultCraftOptionIds, GoodsEntity goods) {
        // 最低价值
        Map<String, String> map = New.hashMap();
        if (singlePriceList.size() > 0 && null != singlePriceList) {
            BigDecimal zdPrice = Collections.min(singlePriceList);
            for (GoodsProductEntity goodsProduct : productList) {
                if (!"copy".equals(goods.getGoodsType())) {
                    if (goods.getStageType() == 0 || goods.getStageType() == 1) {
                        //设置紫云网价格下默认id
                        BigDecimal singlePrice = goodsProduct.getSinglePrice();
                        if (null != singlePrice) {
                            // 有计价单位-->取单价--可能有两个
                            if (singlePrice.compareTo(zdPrice) == 0) {
                                goodsProduct.setDefaultProduct(true);
                                defaultOptionIds = goodsProduct.getOptionIds();
                                defaultCraftOptionIds = goodsProduct.getCraftOptionIds();
                                map.put("defaultOptionIds", defaultOptionIds);
                                map.put("defaultCraftOptionIds", defaultCraftOptionIds);
                                break;
                            }
                        } else {
                            // 无计价单位-->取售价,也可能去2个取值
                            if (goodsProduct.getTotalPrice().compareTo(zdPrice) == 0) {
                                goodsProduct.setDefaultProduct(true);
                                defaultOptionIds = goodsProduct.getOptionIds();
                                defaultCraftOptionIds = goodsProduct.getCraftOptionIds();
                                map.put("defaultOptionIds", defaultOptionIds);
                                map.put("defaultCraftOptionIds", defaultCraftOptionIds);
                                break;
                            }
                        }
                    } else if (goods.getStageType() == 2) {
                        //设置pop平台价格下默认id,因为此时并没有紫云价格
                        BigDecimal singlePricePop = goodsProduct.getSinglePricePop();
                        if (null != singlePricePop) {
                            // 有计价单位-->取单价--可能有两个
                            if (singlePricePop.compareTo(zdPrice) == 0) {
                                goodsProduct.setDefaultProduct(true);
                                defaultOptionIds = goodsProduct.getOptionIds();
                                defaultCraftOptionIds = goodsProduct.getCraftOptionIds();
                                map.put("defaultOptionIds", defaultOptionIds);
                                map.put("defaultCraftOptionIds", defaultCraftOptionIds);
                                break;
                            }
                        } else {
                            // 无计价单位-->取售价,也可能去2个取值
                            if (goodsProduct.getTotalPricePop().compareTo(zdPrice) == 0) {
                                goodsProduct.setDefaultProduct(true);
                                defaultOptionIds = goodsProduct.getOptionIds();
                                defaultCraftOptionIds = goodsProduct.getCraftOptionIds();
                                map.put("defaultOptionIds", defaultOptionIds);
                                map.put("defaultCraftOptionIds", defaultCraftOptionIds);
                                break;
                            }
                        }
                    }
                } else {
                    //如果是复印纸,取expandPrice
                    //将复印纸的箱价放入singlePriceList
                    if (goods.getStageType() == 0 || goods.getStageType() == 1) {
                        if (goodsProduct.getExpandPrice().compareTo(zdPrice) == 0) {
                            goodsProduct.setDefaultProduct(true);
                            defaultOptionIds = goodsProduct.getOptionIds();
                            defaultCraftOptionIds = goodsProduct.getCraftOptionIds();
                            map.put("defaultOptionIds", defaultOptionIds);
                            map.put("defaultCraftOptionIds", defaultCraftOptionIds);
                            break;
                        }
                    } else if (goods.getStageType() == 2) {
                        if (goodsProduct.getExpandPricePop().compareTo(zdPrice) == 0) {
                            goodsProduct.setDefaultProduct(true);
                            defaultOptionIds = goodsProduct.getOptionIds();
                            defaultCraftOptionIds = goodsProduct.getCraftOptionIds();
                            map.put("defaultOptionIds", defaultOptionIds);
                            map.put("defaultCraftOptionIds", defaultCraftOptionIds);
                            break;
                        }
                    }

                }


                //此处逻辑用以判断默认sku设置应是sku价格和最低价格相等的判断,建立在没有计价属性的商品不设置单价的逻辑上
                //若不需要设置singlePrice的商品,也要设置这个属性,则该逻辑需要做相应修改

            }
        }
        return map;
    }

    /**
     * 生成商品编号
     */
    private String builderGoodsBn(Integer categoryId) {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Random random = new Random();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(sdf.format(date));
        stringBuffer.append(String.format("%6d", categoryId).replace(" ", "0"));
        stringBuffer.append(date.getTime());
        stringBuffer.append(String.format("%02d", random.nextInt(99)));
        return stringBuffer.toString();
    }

    /**
     * 按map获得并处理products数据
     *
     * @param goodsProperty
     * @param map
     * @return
     */
    private List<GoodsProductEntity> getAndHandlerProducts(GoodsEntity goodsProperty, HashMap<String, Object> map) {
        List<GoodsProductEntity> goodsProductList = goodsProductService.selectByMap(map);
        if (goodsProductList.size() > 0) {
            String craftOptionIds = goodsProductList.get(0).getCraftOptionIds();
            String optionIds = goodsProductList.get(0).getOptionIds();
            String attributeNames = goodsAttributeService.getAttributeNamesByOptionIds(optionIds);
            String craftNames = goodsAttributeService.getAttributeNamesByOptionIds(craftOptionIds);
            goodsProperty.setAttributeNames(attributeNames);
            goodsProperty.setCraftNames(craftNames);
        }
        // 设置goodsProductList,将option对象赋值进入goodsProduct
        goodsProductService.setOptionByGoodsProductList(goodsProductList);
        // goodsProductService.setCraftOptionByGoodsProductList(goodsProductList);
        // 方案二
        return goodsProductList;
    }

    /**
     * 吨价转令价-->原erp算复印纸箱价方式
     *
     * @param weight
     * @param pack
     * @param sacle
     * @param price
     * @return
     */
    public BigDecimal priceTransformLprice(Integer weight, Integer pack, String sacle, BigDecimal price) {
        BigDecimal length = null;
        BigDecimal num = new BigDecimal(1000 * 1000 * 1000 * 2);
        if (sacle.trim().equalsIgnoreCase("A4"))
            length = new BigDecimal(210 * 297);
        else if (sacle.trim().equalsIgnoreCase("A3"))
            length = new BigDecimal(420 * 297);
        else if (sacle.trim().equalsIgnoreCase("B5"))
            length = new BigDecimal(182 * 257);
        else if (sacle.trim().equalsIgnoreCase("B4"))
            length = new BigDecimal(257 * 364);
        else if (sacle.trim().equalsIgnoreCase("16k"))
            length = new BigDecimal(270 * 195);
        else if (sacle.trim().equalsIgnoreCase("8k"))
            length = new BigDecimal(270 * 390);
        BigDecimal lprice = price.multiply(length).multiply(new BigDecimal(weight)).multiply(new BigDecimal(pack))
                .divide(num, 2, BigDecimal.ROUND_DOWN);
//        if (pack.equals(5))
//            copyAttr.minNum = 56;
        return lprice;
    }

    //判断图片id是否为空
    private Boolean imageVerify(String str) {
        if (StringUtils.isNotBlank(str)) {
            String[] split = str.split(",");
            if (split != null && split.length > 0) {
                return true;
            }
        }
        return false;
    }

    //校验材料是否有价格且不为空值
    private String verifyMaterialPrice(List optionIds, Integer factoryId) {
        if (!(optionIds != null && optionIds.size() > 0)) {
            return "存在部件无材料,请添加材料克重选项";
        }
        Map<String, String> map = New.hashMap();
        Map<String, Object> map2 = New.hashMap();
        map2.put("factory_id", factoryId);
        map2.put("del_flag", 0);
        List<QuoteFactoryMaterialEntity> quoteFactoryMaterialEntities = quoteFactoryMaterialService.selectByMap(map2);
        List<Integer> quoteFactoryMaterialList = New.arrayList();
        if (quoteFactoryMaterialEntities != null && quoteFactoryMaterialEntities.size() > 0) {
            for (int i = 0; i < quoteFactoryMaterialEntities.size(); i++) {
                if (new BigDecimal(0).compareTo(quoteFactoryMaterialEntities.get(i).getMaterialPrice()) != 0) {
                    //不等于零的采取比较
                    quoteFactoryMaterialList.add(quoteFactoryMaterialEntities.get(i).getOptionId());
                }
            }
        }
        if (quoteFactoryMaterialList != null && quoteFactoryMaterialList.size() > 0) {
            for (int j = 0; j < optionIds.size(); j++) {
                if (quoteFactoryMaterialList.indexOf(optionIds.get(j)) == -1) {
                    QuoteAttributeOptionEntity quoteAttributeOptionEntity = quoteAttributeOptionService.selectById(optionIds.get(j).toString());
                    //没找到价格
                    return "材料:" + quoteAttributeOptionEntity.getOptionName() + "克重:" + quoteAttributeOptionEntity.getOptionName2() + "克重id:" + quoteAttributeOptionEntity.getId() + "没有配置材料价格!";
                }
            }
        } else {
            return "所有添加的材料选项均没有找到价格";
        }
        return "ok";
    }

    //查询goodsId，name
    @Override
    public List<GoodsEntity> selectGoodsList(Map<String, Object> params) {
        return this.baseMapper.selectGoodsList(params);
    }

    @Override
    public List<Map<String, Object>> selectPushList() {
        return this.baseMapper.selectPushList();
    }


    /**
     * 根据spu集合获得图文宝商品信息
     *
     * @param goodsIds
     * @return
     */
    @Override
    public R getTwbGoodsVoList(List<Integer> goodsIds,Integer freightId) {
        List<GoodsEntity> goodsEntityList = this.baseMapper.selectBatchIds(goodsIds);
        List<TwbGoodsVo> twbGoodsVoList = New.arrayList();
        for (GoodsEntity goodsEntity : goodsEntityList) {
            TwbGoodsVo twbGoodsVo = new TwbGoodsVo();
            //初始化品牌
            goodsEntity.setBrandId(null);
            goodsEntity.setFreightId(freightId);
            twbGoodsVo.setGoodsEntity(goodsEntity);
            twbGoodsVoList.add(twbGoodsVo);
        }
        if (twbGoodsVoList.size() < 1) {
            return R.error("所选商品数不足1,请重新选择");
        }
        //给第一条数据赋值
        TwbGoodsVo twbGoodsVo = twbGoodsVoList.get(0);
        handlerFirstGoods(twbGoodsVo);
        return R.ok().put("twbGoodsVoList", twbGoodsVoList);
    }
    /**
     * 简化版本商品添加详细信息
     */
    private void handlerFirstGoodsTwo(TwbGoodsVo twbGoodsVo) {
        //第一步:给第一个商品添加sku列表信息
        List<GoodsProductEntity> goodsProductEntityList = goodsProductService.selectByGoodsId(twbGoodsVo.getGoodsEntity().getGoodsId());
        twbGoodsVo.setProductEntityList(goodsProductEntityList);
        //第三步:给第一个商品添加图片信息;
        ImageVo imageVo = new ImageVo();
        List<GoodsImageEntity> goodsImageEntityList = goodsImageService.selectImageEntity(twbGoodsVo.getGoodsEntity().getImageUrls());
        imageVo.setImageEntityList(goodsImageEntityList);
        if (StringUtils.isNotBlank(twbGoodsVo.getGoodsEntity().getInfoUrls())) {
            List<GoodsImageEntity> goodsInfoEntityList = goodsImageService.selectImageEntity(twbGoodsVo.getGoodsEntity().getInfoUrls());
            imageVo.setInfoEntityList(goodsInfoEntityList);
        }
        twbGoodsVo.setImageVo(imageVo);
    }

    /**
     * 给一个商品添加详细信息
     */
    private void handlerFirstGoods(TwbGoodsVo twbGoodsVo) {

        //第一步:给第一个商品添加sku列表信息
        List<GoodsProductEntity> goodsProductEntityList = goodsProductService.selectByGoodsId(twbGoodsVo.getGoodsEntity().getGoodsId());
        twbGoodsVo.setProductEntityList(goodsProductEntityList);
        //第二步骤:给第一个商品添加规格选项信息------>这一步最复杂
        TwbAttributeVo twbAttributeVo = handlerAttributeOption(twbGoodsVo.getGoodsEntity());
        twbGoodsVo.setAttributeVo(twbAttributeVo);
        //第三步:给第一个商品添加图片信息;
        ImageVo imageVo = new ImageVo();
        List<GoodsImageEntity> goodsImageEntityList = goodsImageService.selectImageEntity(twbGoodsVo.getGoodsEntity().getImageUrls());
        imageVo.setImageEntityList(goodsImageEntityList);
        if (StringUtils.isNotBlank(twbGoodsVo.getGoodsEntity().getInfoUrls())) {
            List<GoodsImageEntity> goodsInfoEntityList = goodsImageService.selectImageEntity(twbGoodsVo.getGoodsEntity().getInfoUrls());
            imageVo.setInfoEntityList(goodsInfoEntityList);
        }
        twbGoodsVo.setImageVo(imageVo);
        //第四步:将其设置为不需要再加载
        twbGoodsVo.setNeedLoad(false);
        //第五步:封装分类信息
        GoodsCategoryEntity categoryEntity = goodsCategoryService.selectById(twbGoodsVo.getGoodsEntity().getCategoryId());
        twbGoodsVo.setGoodsCategoryEntity(categoryEntity);
    }


    /**
     * twb处理规格选项方法
     *
     * @param goodsEntity
     */
    private TwbAttributeVo handlerAttributeOption(GoodsEntity goodsEntity) {
        TwbAttributeVo twbAttributeVo = new TwbAttributeVo();
        List<TwbAttributeOptionVo> normalAttributeList = New.arrayList();
        List<TwbAttributeOptionVo> craftAttributeList = New.arrayList();
        List<Integer> optionIds = productBaseInfoService.selectTwbOptionIds(goodsEntity.getGoodsId());

        //新方法二:按照商品绑定的分类找到模板下的optionJson,
        GoodsTemplateEntity template = goodsTemplateService.getTemplateByCatId(goodsEntity.getCategoryId());
        String optionJson = template.getOptionJson();
        net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(optionJson);
        for (int i = 0; i < jsonArray.size(); i++) {
            net.sf.json.JSONObject jsonObject = jsonArray.getJSONObject(i);
            Long attributeId = Long.valueOf(jsonObject.get("attributeId").toString());
            net.sf.json.JSONArray optionIdList = jsonObject.getJSONArray("optionId");
            //根据attributeId获得规格对象
            GoodsAttributeEntity goodsAttributeEntity = goodsAttributeService.selectById(attributeId);
            //根据规格对象获得规格下所有的选项
            //			List<GoodsOptionEntity> goodsOptionEntityList = goodsOptionDao.loadTempOptionsByAttributeId(attributeId);
            List<GoodsOptionEntity> goodsOptionEntityList = goodsOptionDao.selectByOptionIds(optionIdList.join(","));
            List<GoodsOptionEntity> privateGoodsOptionEntityList = goodsOptionDao.selectPrivateOption(attributeId, goodsEntity.getSellerId());
            if (privateGoodsOptionEntityList != null && privateGoodsOptionEntityList.size() > 0) {
                goodsOptionEntityList.addAll(privateGoodsOptionEntityList);
            }
            //下面这可能是规格也可能是工艺
            TwbAttributeOptionVo twbAttributeOptionVo = new TwbAttributeOptionVo();
            twbAttributeOptionVo.setGoodsAttributeEntity(goodsAttributeEntity);
            twbAttributeOptionVo.setGoodsOptionEntityList(goodsOptionEntityList);
            List<Integer> selectOption = New.arrayList();
            for (GoodsOptionEntity goodsOptionEntity : goodsOptionEntityList) {
                Integer optionId = Integer.valueOf(String.valueOf(goodsOptionEntity.getOptionId()));
                if (optionIds.indexOf(optionId) != -1) {
                    //该规格在sku列表中出现
                    selectOption.add(optionId);
                }
            }
            twbAttributeOptionVo.setSelectOption(selectOption);
            if ("normal".equals(goodsAttributeEntity.getAttributeType())) {
                normalAttributeList.add(twbAttributeOptionVo);
            } else {
                craftAttributeList.add(twbAttributeOptionVo);
            }
        }
        twbAttributeVo.setNormalAttributeList(normalAttributeList);
        twbAttributeVo.setCraftAttributeList(craftAttributeList);
        return twbAttributeVo;
    }

    @Override
    public R getTwbGoodsVo(Long goodsId) {
        TwbGoodsVo twbGoodsVo = new TwbGoodsVo();
        GoodsEntity goodsEntity = this.baseMapper.selectById(goodsId);
        twbGoodsVo.setGoodsEntity(goodsEntity);
        handlerFirstGoods(twbGoodsVo);
        return R.ok().put("twbGoodsVo", twbGoodsVo);
    }

    @Override
    public R getUnitLibrary() {
        //取单位库数据
        Map<String, Object> map = New.hashMap();
        map.put("del_flag", 0);
        List<UnitLibraryEntity> unitLibraryList = unitLibraryService.selectByMap(map);
        return R.ok().put("unitLibraryList", unitLibraryList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pushTwbGoodsVoList(List<TwbGoodsVo> list, String userName) {
        List<GoodsEntity> editList = New.arrayList();
        //取出用户编辑过的商品
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getNeedLoad()) {
                editList.add(list.get(i).getGoodsEntity());
                list.remove(i);
                i--;
            }
        }
        //生成用户编辑过的商品
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                pushTwbGoodsVoOne(list.get(i), userName);
            }
        }
        //处理用户未编辑直接发布的
        if(editList != null && editList.size() > 0){
            //editList只改变twb商品发布状态
            for (GoodsEntity goodsEntity : editList) {
                if(!goodsEntity.getTwbPushFlag()){
                    goodsEntity.setCreateTime(new Date());
                }
                goodsEntity.setTwbPushFlag(true);
            }
            this.updateBatchById(editList);
        }
        //抛事件
    }

    /**
     * 图文宝每次发布商品第二代逻辑...发布商品
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pushTwbGoodsVoListNewVersions(List<TwbGoodsVo> list, String userName,Long sellerId) {
        for (TwbGoodsVo twbGoodsVo : list) {
            Long oldGoodsId = twbGoodsVo.getGoodsEntity().getGoodsId();
            if(!twbGoodsVo.getNeedLoad()){
                //生成goods
                GoodsEntity twbGoodsVoGoodsEntity = twbGoodsVo.getGoodsEntity();
                twbHandlerGoodEntity(sellerId, twbGoodsVoGoodsEntity,userName);
                goodsService.insert(twbGoodsVoGoodsEntity);
                //保存图片
                twbSaveImage(userName, twbGoodsVo, twbGoodsVoGoodsEntity);
                //生成productList
                List<TwbItemVo> itemList = twbGoodsVo.getItemList();
                List<Integer> attributeOptionIds = New.arrayList();//建立一个存放product_base_info的容器
                List<GoodsProductEntity> productList = New.arrayList();
                Boolean mark = true;
                String defaultOptionIds = null;
                for (TwbItemVo twbItemVo : itemList) {
                    Map<String, TwbOptionVo> spec = twbItemVo.getSpec();
                    //拿到这个sku的optionIds
                    List<Integer> optionIds = New.arrayList();
                    List<String> optionNames = New.arrayList();
                    for (TwbOptionVo twbOptionVo : spec.values()) {
                        Integer optionId = twbOptionVo.getOptionId();
                        optionIds.add(optionId);
                        optionNames.add(twbOptionVo.getOptionName());
                        if(attributeOptionIds.indexOf(optionId) == -1){
                            attributeOptionIds.add(optionId);
                        }
                    }
                    //规格从小到大排序
                    Collections.sort(optionIds);
                    //赋值工艺
                    List<Integer> cra = twbItemVo.getCra();
                    for (Integer craId : cra) {
                        if(attributeOptionIds.indexOf(craId) == -1){
                            attributeOptionIds.add(craId);
                        }
                    }
                    GoodsProductEntity productEntity = new GoodsProductEntity();
                    handlerSku(twbItemVo,productEntity,twbGoodsVoGoodsEntity.getGoodsId());
                    productEntity.setOptionIds(StringUtils.join(optionIds, ","));
                    productEntity.setCraftOptionIds(StringUtils.join(cra, ","));
                    productEntity.setProductInfo(StringUtils.join(optionNames,","));
                    productEntity.setProductNo(builderGoodsBn(twbGoodsVoGoodsEntity.getCategoryId()));
                    if(mark){
                        productEntity.setDefaultProduct(true);
                        mark = false;
                        defaultOptionIds = StringUtils.join(optionIds, ",");
                    }
                    productList.add(productEntity);
                }
                goodsProductService.insertBatch(productList);
                //生成productBaseInfo
                //保存第三步:修改product_base_info上的信息
                Map<String, Object> map = New.hashMap();
                map.put("goodsId",twbGoodsVoGoodsEntity.getGoodsId());
                map.put("createUser",userName);
                map.put("categoryId",twbGoodsVo.getGoodsEntity().getCategoryId());
                List<ProductBaseInfoEntity> productBaseInfoEntityList = getProductData(attributeOptionIds,map);
                //处理影响sku算价和默认
                handlerProductBaseInfoDefaultAndTemp(productBaseInfoEntityList,twbGoodsVo.getGoodsEntity().getCategoryId(),defaultOptionIds);
                productBaseInfoService.insertBatch(productBaseInfoEntityList);
                //完.
            }else{
                handlerFirstGoodsTwo(twbGoodsVo);
                //生成goods
                GoodsEntity twbGoodsVoGoodsEntity = twbGoodsVo.getGoodsEntity();
                twbHandlerGoodEntity(sellerId, twbGoodsVoGoodsEntity,userName);
                goodsService.insert(twbGoodsVoGoodsEntity);
                twbSaveImage(userName, twbGoodsVo, twbGoodsVoGoodsEntity);
                List<GoodsProductEntity> productEntityList = twbGoodsVo.getProductEntityList();
                for (GoodsProductEntity productEntity : productEntityList) {
                    productEntity.setGoodsId(twbGoodsVoGoodsEntity.getGoodsId());
                    productEntity.setProductId(null);
                    productEntity.setCreateName(userName);
                    productEntity.setCreateTime(null);
                    productEntity.setProductNo(builderGoodsBn(twbGoodsVoGoodsEntity.getCategoryId()));
                }
                goodsProductService.insertBatch(productEntityList);
                Map<String, Object> map = New.hashMap();
                map.put("goods_id",oldGoodsId);
                map.put("del_flag",0);
                List<ProductBaseInfoEntity> productBaseInfoEntityList = productBaseInfoService.selectByMap(map);
                for (ProductBaseInfoEntity productBaseInfoEntity : productBaseInfoEntityList) {
                    productBaseInfoEntity.setId(null);
                    productBaseInfoEntity.setGoodsId(twbGoodsVoGoodsEntity.getGoodsId());
                    productBaseInfoEntity.setCreateUser(userName);
                    productBaseInfoEntity.setCreateDate(null);
                }
                productBaseInfoService.insertBatch(productBaseInfoEntityList);
            }
        }
    }

    private void twbHandlerGoodEntity(Long sellerId, GoodsEntity twbGoodsVoGoodsEntity,String userName) {
        twbGoodsVoGoodsEntity.setSellerId(sellerId.intValue());
        Long goodsId = twbGoodsVoGoodsEntity.getGoodsId();
        twbGoodsVoGoodsEntity.setZiyunGoodsId(goodsId);
        twbGoodsVoGoodsEntity.setGoodsId(null);
        twbGoodsVoGoodsEntity.setGoodsNo(builderGoodsBn(twbGoodsVoGoodsEntity.getCategoryId()));
        twbGoodsVoGoodsEntity.setTwbPushFlag(true);
        twbGoodsVoGoodsEntity.setCreateTime(null);
        twbGoodsVoGoodsEntity.setCreateName(userName);
        twbGoodsVoGoodsEntity.setDefaultGoods(0);
        twbGoodsVoGoodsEntity.setSelf(false);
    }

    private void twbSaveImage(String userName, TwbGoodsVo twbGoodsVo, GoodsEntity twbGoodsVoGoodsEntity) {
        ImageVo imageVo = twbGoodsVo.getImageVo();
        Map<String, Object> data = New.hashMap();
        data.put("userName",userName);
        data.put("goodsId",twbGoodsVoGoodsEntity.getGoodsId());
        List<GoodsImageEntity> imageEntityList = imageVo.getImageEntityList();
        String imageUrlStr = pushHandlerImageList(imageEntityList, data);
        List<GoodsImageEntity> infoEntityList = imageVo.getInfoEntityList();
        String infoUrlsStr = pushHandlerImageList(infoEntityList, data);
        //回写图片
        GoodsEntity goodsEntity = new GoodsEntity();
        goodsEntity.setGoodsId(twbGoodsVoGoodsEntity.getGoodsId());
        goodsEntity.setImageUrls(imageUrlStr);
        goodsEntity.setInfoUrls(infoUrlsStr);
        goodsService.updateById(goodsEntity);
    }

    private String pushHandlerImageList(List<GoodsImageEntity> imageEntityList, Map<String,Object> data) {
        if(imageEntityList != null && imageEntityList.size() > 0){
            String userName = String.valueOf(data.get("userName"));
            Long goodsId = Long.valueOf(String.valueOf(data.get("goodsId")));
            for (GoodsImageEntity goodsImageEntity : imageEntityList) {
                goodsImageEntity.setRelationId(goodsId);
                goodsImageEntity.setCreateName(userName);
                goodsImageEntity.setCreateTime(null);
            }
            goodsImageService.insertBatch(imageEntityList);
            List<Long> ids = New.arrayList();
            for (GoodsImageEntity goodsImageEntity : imageEntityList) {
                ids.add(goodsImageEntity.getId());

            }
            return StringUtils.join(ids,",");
        }else{
            return null;
        }
    }


    /**
	 * 图文宝每次发布商品
	 ** @param twbGoodsVo
	 */
	private void pushTwbGoodsVoOne(TwbGoodsVo twbGoodsVo,String userName) {
		//保存第一步:保存基本spu信息
		//stepOne:保存图片信息
		ImageVo imageVo = twbGoodsVo.getImageVo();
		String imageUrls = twbGoodsVo.getGoodsEntity().getImageUrls();
		String infoUrls = twbGoodsVo.getGoodsEntity().getInfoUrls();
		Map<String, Object> data = New.hashMap();
		data.put("userName",userName);
		data.put("goodsId",twbGoodsVo.getGoodsEntity().getGoodsId());
		//主图信息保存
		List<GoodsImageEntity> imageEntityList = imageVo.getImageEntityList();
		String imageUrlStr = handlerImageList(imageEntityList, data,imageUrls);
		twbGoodsVo.getGoodsEntity().setImageUrls(imageUrlStr);
		//详情图信息保存
		List<GoodsImageEntity> infoEntityList = imageVo.getInfoEntityList();
		String infoUrlStr = handlerImageList(infoEntityList, data,infoUrls);
		twbGoodsVo.getGoodsEntity().setInfoUrls(infoUrlStr);
		//stepTwo:保存spu信息
        if(!twbGoodsVo.getGoodsEntity().getTwbPushFlag()){
            //未发布的将发布时间设置为现在
            twbGoodsVo.getGoodsEntity().setCreateTime(new Date());
        }
        twbGoodsVo.getGoodsEntity().setTwbPushFlag(true);
		this.baseMapper.updateById(twbGoodsVo.getGoodsEntity());
		//保存第二步:保存sku表上的信息
		List<GoodsProductEntity> productEntityList = twbGoodsVo.getProductEntityList();
		//先将所有productEntiyList的上下架状态置为删除
		for (GoodsProductEntity productEntity : productEntityList) {
			productEntity.setMarketable("delete");
            productEntity.setDefaultProduct(false);
		}
		List<TwbItemVo> itemList = twbGoodsVo.getItemList();
        //定义一个新增加的productEntityList
        List<GoodsProductEntity> newProductList = New.arrayList();
		List<Integer> attributeOptionIds = New.arrayList();
		for (TwbItemVo twbItemVo : itemList) {
			//定义一个方法,按optionIds查sku列表,返回匹配的sku,将其值放进去
			handlerSkuByItem(twbItemVo,productEntityList,newProductList,attributeOptionIds,twbGoodsVo.getGoodsEntity().getGoodsId(),twbGoodsVo.getGoodsEntity().getCategoryId(),userName);
		}
		//设置默认商品productEntityList/newProductList
        setDefaultSkuByIter(productEntityList,newProductList);
		//stepThree:更新旧sku信息,生成新sku信息
		goodsProductService.updateBatchById(productEntityList);
		if(newProductList.size() > 0){
			goodsProductService.insertBatch(newProductList);
        }
		//保存第三步:修改product_base_info上的信息
        Map<String, Object> map = New.hashMap();
		map.put("goodsId",twbGoodsVo.getGoodsEntity().getGoodsId());
		map.put("createUser",userName);
		map.put("categoryId",twbGoodsVo.getGoodsEntity().getCategoryId());
		List<ProductBaseInfoEntity> productBaseInfoEntityList = getProductData(attributeOptionIds,map);
		String defaultOptionIds = null;
		for (GoodsProductEntity productEntity : productEntityList) {
			if(productEntity.getDefaultProduct()){
				defaultOptionIds = productEntity.getOptionIds();
			}

		}
		//先删除原有的数据
		productBaseInfoService.deleteProductBaseInfoByGoodsId(twbGoodsVo.getGoodsEntity().getGoodsId());
		//处理影响sku算价和默认
		handlerProductBaseInfoDefaultAndTemp(productBaseInfoEntityList,twbGoodsVo.getGoodsEntity().getCategoryId(),defaultOptionIds);
		productBaseInfoService.insertBatch(productBaseInfoEntityList);

	}

    private void setDefaultSkuByIter(List<GoodsProductEntity> productEntityList, List<GoodsProductEntity> newProductList) {
        BigDecimal bottomPrice = new BigDecimal(1000000);
        Boolean mark = true;
        for (GoodsProductEntity productEntity : productEntityList) {
            if(productEntity.getMarketable().equals("puton")){
                if(mark){
                    bottomPrice = productEntity.getTotalPrice();
                    mark = false;
                }
                if(bottomPrice.compareTo(productEntity.getTotalPrice()) == 1){
                    bottomPrice = productEntity.getTotalPrice();
                }
            }
        }
        for (GoodsProductEntity productEntity : newProductList) {
            if(productEntity.getMarketable().equals("puton")) {
                if (bottomPrice.compareTo(productEntity.getTotalPrice()) == 1) {
                    bottomPrice = productEntity.getTotalPrice();
                }
            }
        }
        for (GoodsProductEntity productEntity : productEntityList) {
            if(productEntity.getMarketable().equals("puton")) {
                if (bottomPrice.compareTo(productEntity.getTotalPrice()) == 0) {
                    productEntity.setDefaultProduct(true);
                    return;
                }
            }
        }
        for (GoodsProductEntity productEntity : newProductList) {
            if(productEntity.getMarketable().equals("puton")) {
                if (bottomPrice.compareTo(productEntity.getTotalPrice()) == 1) {
                    productEntity.setDefaultProduct(true);
                    return;
                }
            }
        }
        if(mark){
            throw new RRException("无上架商品异常信息!");
        }else{
            throw new RRException("设置默认商品失败");
        }
    }

    /**
	 * 处理productBAseInfoList的默认和影响算价信息
	 * @param productBaseInfoList
	 */
	private void handlerProductBaseInfoDefaultAndTemp(List<ProductBaseInfoEntity> productBaseInfoList,Integer categoryId,String defaultOptionIds) {
		List<Integer> ids = changeStr2List(defaultOptionIds);
		GoodsTemplateEntity templateByCat = goodsTemplateService.getTemplateByCatId(categoryId);
		long influenceSkuTotalPrice = templateByCat.getInfluenceSkuTotalPrice();
		for(int i = 0;i<productBaseInfoList.size();i++){
			if(influenceSkuTotalPrice != 0){
				if(productBaseInfoList.get(i).getAttributeId() == influenceSkuTotalPrice){
					productBaseInfoList.get(i).setInfluenceCraftType("sku_price");
				}else{
					productBaseInfoList.get(i).setInfluenceCraftType("none");
				}
			}else{
				productBaseInfoList.get(i).setInfluenceCraftType("none");
			}
			if(ids.indexOf(productBaseInfoList.get(i).getOptionId()) != -1){
				productBaseInfoList.get(i).setWhetherDefault(1);
			}
		}

	}

	/**
	 * 根据规格信息,获得productBaseInfoList
	 * @param attributeOptionIds
	 * @return
	 */
	private List<ProductBaseInfoEntity> getProductData(List<Integer> attributeOptionIds,Map<String, Object> map) {
		List<ProductBaseInfoEntity> productBaseInfoEntityList = New.arrayList();
		Long goodsId = Long.valueOf(String.valueOf(map.get("goodsId")));
		String createUser = String.valueOf(map.get("createUser"));
		Integer categoryId = Integer.valueOf(String.valueOf(map.get("categoryId")));
		List<GoodsOptionEntity> goodsOptionEntityList = goodsOptionDao.selectBatchIds(attributeOptionIds);
		for (GoodsOptionEntity goodsOptionEntity : goodsOptionEntityList) {
			ProductBaseInfoEntity productBaseInfoEntity = new ProductBaseInfoEntity();
			productBaseInfoEntity.setGoodsId(goodsId);
			productBaseInfoEntity.setAttributeId(Integer.valueOf(String.valueOf(goodsOptionEntity.getAttributeId())));
			productBaseInfoEntity.setOptionId(Integer.valueOf(String.valueOf(goodsOptionEntity.getOptionId())));
			productBaseInfoEntity.setCreateUser(createUser);
			productBaseInfoEntity.setCategoryId(categoryId);
			productBaseInfoEntityList.add(productBaseInfoEntity);
		}
		return productBaseInfoEntityList;
	}

	/**
	 * 按照itemList的值处理productList
	 * @param twbItemVo
	 * @param productEntityList
	 */
	private void handlerSkuByItem(TwbItemVo twbItemVo,List<GoodsProductEntity> productEntityList,List<GoodsProductEntity> newProductList,List<Integer> attributeOptionIds,Long goodsId,Integer categoryId,String username){
		Map<String, TwbOptionVo> spec = twbItemVo.getSpec();
		//拿到这个sku的optionIds
        List<Integer> optionIds = New.arrayList();
        List<String> optionNames = New.arrayList();
        for (TwbOptionVo twbOptionVo : spec.values()) {
			Integer optionId = twbOptionVo.getOptionId();
			optionIds.add(optionId);
            optionNames.add(twbOptionVo.getOptionName());
			if(attributeOptionIds.indexOf(optionId) == -1){
				attributeOptionIds.add(optionId);
			}
		}
		//赋值工艺
		List<Integer> cra = twbItemVo.getCra();
		for (Integer craId : cra) {
			if(attributeOptionIds.indexOf(craId) == -1){
				attributeOptionIds.add(craId);
			}
		}
		//找到productEntityList中规格匹配的,修改其值
		for(int i = 0;i<productEntityList.size();i++){
			List<Integer> ids = changeStr2List(productEntityList.get(i).getOptionIds());
			Collections.sort(ids);
			Collections.sort(optionIds);
			if(ids.toString().equals(optionIds.toString())){
				//修改这个productEntity的值
				handlerSku(twbItemVo,productEntityList.get(i),goodsId);
				return;
			}
		}
		//当循环走完,尚未匹配上sku,则该规格新增
		GoodsProductEntity productEntity = new GoodsProductEntity();
		handlerSku(twbItemVo,productEntity,goodsId);
        productEntity.setOptionIds(StringUtils.join(optionIds, ","));
        productEntity.setCraftOptionIds(StringUtils.join(cra, ","));
        productEntity.setProductInfo(StringUtils.join(optionNames,","));
        productEntity.setCreateName(username);
        productEntity.setProductNo(builderGoodsBn(categoryId));
		newProductList.add(productEntity);
	}

	/**
	 * 处理sku的具体方法
	 */
	private void handlerSku(TwbItemVo twbItemVo,GoodsProductEntity productEntity,Long goodsId){
        productEntity.setGoodsId(goodsId);
		productEntity.setStore(twbItemVo.getStore());//unit minBuyNum marketable weight totalPrice cost
		productEntity.setUnit(twbItemVo.getUnit());
		productEntity.setMarketable(twbItemVo.getMarketable());
        productEntity.setMinBuyNum(twbItemVo.getMinBuyNum());
		productEntity.setWeight(twbItemVo.getWeight());
		productEntity.setTotalPrice(twbItemVo.getTotalPrice());
		productEntity.setCost(twbItemVo.getCost());
	}

	/**
	 * 处理图片list信息,未生成的生成,(已生成的修改或删除)
	 * @param imageList
	 */
	private String handlerImageList(List<GoodsImageEntity> imageList,Map<String,Object> data,String oldUrls){
		String userName = String.valueOf(data.get("userName"));
		Long goodsId = Long.valueOf(String.valueOf(data.get("goodsId")));
		List<GoodsImageEntity> needInsertList = New.arrayList();
		for(int i = 0;i<imageList.size();i++){
			Long id = imageList.get(i).getId();
			if(imageList.get(i).getId() == null || "".equals(imageList.get(i).getId())){
				imageList.get(i).setCreateName(userName);
				imageList.get(i).setRelationId(goodsId);
				needInsertList.add(imageList.get(i));
				imageList.remove(i);
				i--;
			}else{
				//需要修改的,暂不需要此功能块
			}
		}
		List<Integer> urls = changeStr2List(oldUrls);
		StringBuffer stringBuffer = new StringBuffer();
        List<Long> ids = New.arrayList();
        if(imageList.size() > 0){
			for (GoodsImageEntity goodsImageEntity : imageList) {
				stringBuffer.append(goodsImageEntity.getId());
				stringBuffer.append(",");
                ids.add(goodsImageEntity.getId());
				if(urls != null && urls.size() > 0){
					int index = urls.indexOf(Integer.valueOf(String.valueOf(goodsImageEntity.getId())));
					if(index != -1){
						urls.remove(index);
					}
				}
			}
		}
		if(needInsertList.size() > 0){
			goodsImageService.insertBatch(needInsertList);
			for (GoodsImageEntity goodsImageEntity : needInsertList) {
				stringBuffer.append(goodsImageEntity.getId());
				stringBuffer.append(",");
                ids.add(goodsImageEntity.getId());
			}
		}
		if(urls != null && urls.size() > 0){
			goodsImageService.flagDelImage(urls);
		}
//		return stringBuffer.toString();
        return StringUtils.join(ids,",");
	}

	/**
	 *字符串转为Integer数组
	 */
	private List<Integer> changeStr2List(String str){
		if(StringUtils.isNotBlank(str)){
			String[] split = str.split(",");
			List<Integer> ids = New.arrayList();
			for(int j = 0;j<split.length;j++){
				if(StringUtils.isNotBlank(split[j])){
					ids.add(Integer.valueOf(split[j]));
				}
			}
			return ids;
		}else{
			return null;
		}
	}


	@Override
	public R getTwbGoodsList(Map params) {
		Page<TwbGoodsListVo> goodsEntityPage = new Page<>();////marketable current size total
		goodsEntityPage.setSize((Integer)params.get("size"));
		goodsEntityPage.setCurrent((Integer)params.get("current"));
//		String marketable = (String) params.get("marketable");
//		Long sellerId = Long.valueOf(String.valueOf(params.get("sellerId")));
		goodsEntityPage.setRecords(this.baseMapper.queryTwbGoodsList(goodsEntityPage,params));

		return R.ok().put("goodsEntityPage",goodsEntityPage);
	}

	@Override
	public R editTwbGoodsPrice(Long goodsId) {
		List<TwbEditPriceVo> twbEditPriceVoList = this.baseMapper.editTwbGoodsPrice(goodsId);
		return R.ok().put("twbEditPriceVoList",twbEditPriceVoList);
	}

    /**
     * 添加图文宝分类
     *
     * @param goods
     * @return
     */
    public R goodsTwbUpdate(GoodsEntity goods) {
        Integer sellerId = goods.getSellerId();
        Long goodsId = goods.getGoodsId();
        Long twbCategory = goods.getTwbCategory();
        Map<String, Object> map = new HashMap<>();
        if (sellerId != 1) {
            return R.error("非紫云网商品不能添加图文宝分类！");
        }
        if (twbCategory == 0) {
            map.put("twbCategory", twbCategory);
            map.put("defaultGoods", 0);
            this.baseMapper.updateByMap(map, goodsId);
        } else {
            map.put("twbCategory", twbCategory);
            map.put("defaultGoods", 1);
            this.baseMapper.updateByMap(map, goodsId);
        }
        return R.ok();
    }

    /**
     * 图文宝列表编辑价格修改保存
     * @param list
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveTwbGoodsListPrice(List<TwbEditPriceVo> list) {
        List<GoodsProductEntity> goodsProductList = New.arrayList();
        for (TwbEditPriceVo twbEditPriceVo : list) {
            GoodsProductEntity productEntity = new GoodsProductEntity();
            productEntity.setProductId(Long.valueOf(twbEditPriceVo.getProductId()));
            productEntity.setTotalPrice(twbEditPriceVo.getTotalPrice());
            productEntity.setCost(twbEditPriceVo.getCost());
            productEntity.setWeight(twbEditPriceVo.getWeight());
            goodsProductList.add(productEntity);
        }
        goodsProductService.updateBatchById(goodsProductList);
        return R.ok();
    }

    /**
     * 获取图文宝分类及其下面的商品
     * @return
     */
    @Override
    public R getTwbCateAndGoods(Long sellerId) {
        //获得所有的图文宝分类
        Map<String, Object> map = New.hashMap();
        map.put("del",0);
        List<StoreGoodsCategoryTwdEntity> storeGoodsCategoryTwdList = storeGoodsCategoryTwdService.selectByMap(map);
        //获得所有的商户商品信息
//        List<GoodsEntity> goodsEntityList = this.selectList(new EntityWrapper<GoodsEntity>()
//                .eq("disabled", 0)
//                .eq("seller_id", sellerId)
//                .ne("ziyun_goods_id", 0));
        List<GoodsEntity> goodsEntityList = this.baseMapper.selectTwbSelfGoodsAndSellerPushStatus(sellerId);
        Map<String, Object> resultMap = New.hashMap();
        List<TwbCategoryAndGoodsVo> faseStoreTwbCatAndGoodsVo = New.arrayList();
        List<TwbCategoryAndGoodsVo> materialStoreTwbCatAndGoodsVo = New.arrayList();
        List<StoreGoodsCategoryTwdEntity> faseStoreGoodsCategoryTwdList = New.arrayList();
        List<StoreGoodsCategoryTwdEntity> materialStoreGoodsCategoryTwdList = New.arrayList();
        //处理分类信息
        for (StoreGoodsCategoryTwdEntity storeGoodsCategoryTwdEntity : storeGoodsCategoryTwdList) {
            TwbCategoryAndGoodsVo twbCategoryAndGoodsVo = new TwbCategoryAndGoodsVo();
            twbCategoryAndGoodsVo.setCategoryEntity(storeGoodsCategoryTwdEntity);
            List<GoodsEntity> goodsEntityList1 = queryGoodsListByTwbCatId(storeGoodsCategoryTwdEntity.getCategoryId(), goodsEntityList);
            twbCategoryAndGoodsVo.setGoodsList(goodsEntityList1);
            if(storeGoodsCategoryTwdEntity.getCategoryType().equals("fastStore")){
                faseStoreTwbCatAndGoodsVo.add(twbCategoryAndGoodsVo);
            }else{
                materialStoreTwbCatAndGoodsVo.add(twbCategoryAndGoodsVo);
            }
        }
        resultMap.put("fastStores",faseStoreTwbCatAndGoodsVo);
        resultMap.put("materialStores",materialStoreTwbCatAndGoodsVo);
        return R.ok().put("resultMap",resultMap);
    }

    @Override
    public List<Long> handHide(Integer categoryId, Boolean hide) {
        List<Long> goodsIds = this.baseMapper.beforeUpdateHideGoodsByCategoryId(categoryId,hide);
        this.baseMapper.updateHideGoodsByCategoryId(categoryId,hide);//BatchUpdateGoodsEvent
        batchGoodsEvent(goodsIds);
        return goodsIds;
    }

    private void batchGoodsEvent(List<Long> goodsIds) {
        log.info(">>>>> 开始刷新单个缓存spu" + StringUtils.join(goodsIds,",") + " <<<<<");
        BatchUpdateGoodsEvent build = BatchUpdateGoodsEvent.builder().source(this).goodsIds(StringUtils.join(goodsIds, ",")).build();
        EventBusPusher.syncPost(build);
        log.info(">>>>> 结束更新spu <<<<<");
    }

    @Override
    public void twbGoodsEvent(List<TwbGoodsVo> list) {
        List<Long> goodsIds = New.arrayList();
        for (TwbGoodsVo twbGoodsVo : list) {
            goodsIds.add(twbGoodsVo.getGoodsEntity().getGoodsId());
        }
        batchGoodsEvent(goodsIds);
    }

    /**
     * 图文宝批量操作商品
     * @param goodsIds
     * @return
     */
    @Override
    public R twbListOperation(List<Long> goodsIds,String marketable) {
        this.baseMapper.twbListOperation(goodsIds,marketable);
        batchGoodsEvent(goodsIds);
        return R.ok();
    }

    /**
     * 按图文宝分类id获取商户图文宝商品
     */
    private List<GoodsEntity> queryGoodsListByTwbCatId(Integer twbCategory,List<GoodsEntity> goodsEntityList){
        List<GoodsEntity> goodsList = New.arrayList();
        for(int i = 0;i<goodsEntityList.size();i++){
            if(goodsEntityList.get(i).getTwbCategory().intValue() == twbCategory.intValue() ){
                goodsList.add(goodsEntityList.get(i));
            }
        }
        return goodsList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void twbGoodsImageBug() {
        List<GoodsEntity> goodsBugData = this.baseMapper.getTwbGoodsImageBugData();
        for (GoodsEntity goodsBugDatum : goodsBugData) {
            String imageUrls = goodsBugDatum.getImageUrls();
            List<GoodsImageEntity> goodsImageEntityList = goodsImageService.selectImageEntity(imageUrls);
            if(goodsImageEntityList != null && goodsImageEntityList.size() > 0){
                for (GoodsImageEntity goodsImageEntity : goodsImageEntityList) {
                    goodsImageEntity.setId(null);
                    goodsImageEntity.setRelationId(goodsBugDatum.getGoodsId());
                    goodsImageEntity.setType(0);
                    goodsImageEntity.setCreateName("twb数据修复");
                    goodsImageEntity.setCreateTime(new Date());
                }
                goodsImageService.insertBatch(goodsImageEntityList);
                List<Long> imageIdList = New.arrayList();
                for (GoodsImageEntity goodsImageEntity : goodsImageEntityList) {
                    imageIdList.add(goodsImageEntity.getId());
                }
                GoodsEntity goodsEntityTemp = new GoodsEntity();
                goodsEntityTemp.setImageUrls(StringUtils.join(imageIdList,","));
                goodsEntityTemp.setGoodsId(goodsBugDatum.getGoodsId());
                this.updateById(goodsEntityTemp);
            }
        }
    }

    /**
     * 小程序接口实现,获得商品商品数量统计
     * @param sellerId
     * @return
     */
    @Override
    public TwbStateCollectVo getTwbGoodsStateCount(Long sellerId) {
        return this.baseMapper.getTwbGoodsStateCount(sellerId);
    }


}
